0. Java
-
使用 map 存储,判断 target-num 是否在 map 中(需要遍历两次数组):
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> valueIdxMap = new HashMap<>(); int[] idx = new int[2]; for (int i = 0; i < nums.length; ++i) { valueIdxMap.put(nums[i], i); } for (int i = 0; i < nums.length; ++i) { int other = target - nums[i]; if (valueIdxMap.containsKey(other)) { int pos = valueIdxMap.get(other); if (pos == i) { continue; } idx[0] = i; idx[1] = pos; return idx; } } throw new IllegalArgumentException("No solution"); }
-
仍然使用 map,不过这次 map中存放的是元素的补,此时仅需要遍历数组一次:
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> complementary = new HashMap<>(); int[] result = new int[2]; for (int i = 0; i < nums.length; ++i) { if (!complementary.containsKey(nums[i])) { complementary.put(target-nums[i], i); } else { result[0] = complementary.get(nums[i]); result[1] = i; return result; } } throw new IllegalArgumentException("No solution"); }
1. Python
class Solution(object):
def twoSum(self, nums, target):
d = defaultdict(int)
for i, num in enumerate(nums):
if num not in d:
d[target-num] = i
else:
return [d[num], i]
这里所使用的字典 d,建立 值 与 与其关于 target 成互补关系的值的下标;