1.题目要求
2.代码详情
java:暴力求解法+hashmap法
class Solution {
// 方法一:暴力求解法
// public int[] twoSum(int[] nums, int target) {
// int n = nums.length;
// for (int i=0; i<n; i++){
// for (int j=i+1; j<n; j++){
// if (nums[i]+nums[j] == target){
// return new int[]{i,j};
// }
// }
// }
// return null;
// }
// 方法二:hashmap方法
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
for(int i=0; i<nums.length; i++){
if (hashmap.containsKey(target-nums[i])){
int j=hashmap.get(target-nums[i]);
return new int[]{j,i};
}
hashmap.put(nums[i],i);
}
return new int[0];
}
}
python:暴力求解:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
return [i,j]
return []
python:排序+双指针
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
temp = nums.copy()
temp.sort()
i=0
j = len(nums)-1
while i < j:
if (temp[i] + temp[j]) > target:
j -= 1
elif (temp[i] + temp [j]) < target:
i += 1
else:
break
p = nums.index(temp[i])
nums.pop(p)
k = nums.index(temp[j])
if k >= p:
k = k+1
return [p, k]