题目
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
(1)方法一:双重for循环,简单粗暴
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
for(int i = 0;i < nums.length ;i++){
for(int j = nums.length-1;j>i;j--){
if(nums[i] + nums[j] == target){
index[0] = i;
index[1] = j;
return index;
}
}
}
return index;
}
}
结果(1)

方法二:用map,先减去一个值,判断剩下的值是否在map中,不在的添加key-value
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i < nums.length ;i++){
int other_num = target - nums[i];
if(null != map.get(other_num)){
index[0] = map.get(other_num);
index[1] = i;
return index;
}
map.put(nums[i],i);
}
return index;
}
}
结果(2)
