只要需找到之前的值,则很适合hash,具体用哪种hash思路,则看情况;由于本题要存放遍历过的内容,即元素(k)和下标(v),因而适合map去处理
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
//记录遍历过的值
Map<Integer, Integer> history = new HashMap<>();
for(int i = 0;i < nums.length;i++){
int temp = target - nums[i];
Integer historyValue = history.get(temp);
//找到了匹配结果
if(historyValue != null && historyValue != i){
res[0] = i;
res[1] = historyValue;
break;
} else {
history.put(nums[i], i);
}
}
return res;
}
}