如有错误请提出!谢谢
https://dailycode.youkuaiyun.com/practice/2190920
答案选A
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> cache = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int distance = target - nums[i];
if (cache.containsKey(distance)) {
return new int[] { cache.get(distance), i };
} else {
cache.put(nums[i], i);
}
}
return new int[] {};
}
}
通过HashMap去存储读取到的每一个数的位置以及它与target的插值
每次循环将得到的数与HashMap中所得到之前每个数的差对比,当两者相等时,则输出两数位置