You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
代码
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> datas = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if(datas.containsKey(nums[i])) {
Integer k = datas.get(nums[i]);
return new int[]{k,i};
}else {
int k = target - nums[i];
datas.put(k,i);
}
}
throw new RuntimeException("未找到");
}
分析
主要是利用map集合来存储值,存储的是下一下要找的值和当前的索引,然后找到的时候就可以知道这两个索引