@(labuladong的算法小抄)[nSum]
leetcode 1. 两数之和
题目描述
解题思路
参考:labuladong的算法小抄P315
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> index = new HashMap<>();
/* 元素映射到对应的下标 */
for (int i = 0; i < nums.length; i++) {
index.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int other = target - nums[i];
/* 如果other存在,且不是nums[i]自己 */
if (index.containsKey(other) && index.get(other) != i) {
return new int[]{i, index.get(other)};
}
}
return new int[]{-1, -1};
}
}