给定一个数组和一个整数,返回数组中两数之和等于目标整数的下标。
假定每种输入只有一个输出,数组中每个元素只能使用一次。
举例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
python实现
1:暴力法(简单遍历),时间复杂度o(n^2)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(0,len(nums)-1):
for j in range(i+1,len(nums)):
if(nums[i]+nums[j] == target):
return [i,j]
2:利用dict判断,时间复杂度o(n)
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i in range(0,len(nums)):
rest = target-nums[i]
if rest in dic:
return [dic[rest],i]
else:
dic[nums[i]]=i
java实现
1:暴力法,时间复杂度o(n^2)
public int[] twoSum(int[] nums, int target) {
for(int i=0;i<nums.length;i++) {
for(int j=i+1;j<nums.length;j++) {
if(nums[i] +nums[j] == target){
return new int[] {i,j};
}
}
}
return null;
}
2:HashMap方法,时间复杂度o(n)
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> container = new HashMap<Integer,Integer>();
for(int i =0;i<nums.length;i++) {
int restValue = target-nums[i];
if(container.containsKey(restValue)) {
return new int[] {container.get(restValue),i};
}
else {
container.put(nums[i], i);
}
}
return null;
}
C实现
1:暴力法,时间复杂度o(n^2)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int *answer = (int *)malloc(sizeof(int) * 2);
for(int i=0;i<numsSize-1;i++){
for(int j=i+1;j<numsSize;j++){
if(nums[i]+nums[j] == target){
answer[0] = i;
answer[1] = j;
return answer;
}
}
}
return NULL;
}
本文详细解析了经典的两数之和算法问题,包括暴力法和利用哈希表的优化解决方案,提供了Python、Java和C语言的实现代码,旨在帮助读者理解和掌握高效查找数组中两数相加等于特定目标值的技巧。
2633

被折叠的 条评论
为什么被折叠?



