int[] twoSum(int[] nums, int target) { int n = nums.length; index<Integer, Integer> index = new HashMap<>(); // 构造一个哈希表:元素映射到相应的索引 for (int i = 0; i < n; i++) index.put(nums[i], i);
for (int i = 0; i < n; i++) { int other = target - nums[i]; // 如果 other 存在且不是 nums[i] 本身 if (index.containsKey(other) && index.get(other) != i) returnnewint[] {i, index.get(other)}; }
returnnewint[] {-1, -1}; }
这样,由于哈希表的查询时间为 O(1),算法的时间复杂度降低到 O(N),但是需要 O(N) 的空间复杂度来存储哈希表。不过综合来看,是要比暴力解法高效的。 我觉得 Two Sum 系列问题就是想教我们如何使用哈希表处理问题。我们接着往后看。
TwoSum II
这里我们稍微修改一下上面的问题。我们设计一个类,拥有两个 API:
1 2 3 4 5 6
classTwoSum{ // 向数据结构中添加一个数 number publicvoidadd(int number); // 寻找当前数据结构中是否存在两个数的和为 value publicbooleanfind(int value); }
classTwoSum{ Set<Integer> sum = new HashSet<>(); List<Integer> nums = new ArrayList<>(); publicvoidadd(int number){ // 记录所有可能组成的和 for (int n : nums) sum.add(n + number); nums.add(number); }