class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int needNum = target - nums[i];
if (map.containsKey(needNum)) {// 找到表里已经有对应的值
return new int[] { map.get(needNum), i };
} else {
map.put(nums[i], i);// 若没有就把数值和索引放入表中
}
}
return new int[] { 0 };// 若遍历之后没找到要的数
}
}
用的是评论区kxACE的方法