Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
寻找sum为target的组合,可以想到使用map
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];//设置数组的大小 作为返回值
Map<Integer,Integer> map = new HashMap<Integer,Integer>();//我竟然一开始忘了写new
for(int i =0;i<nums.length;i++){
if(map.containsKey(target - nums[i])){
result[1] = i;
result[0] = map.get(target - nums[i]);
return result;
}
map.put(nums[i],i);//本来一开始把这个写在前面 也就是先塞进map再来寻找,但是后来发现会出现自己和自己相加的情况,于是放在后面
}
return result;
}
}