两数之和
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
题目来源:力扣(LeetCode)
题目链接:https://leetcode-cn.com/problems/two-sum
题目著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我的解答
我在做这道题的时候没想那么多,就直接来了两层循环:
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length - 1; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { return new int[] {i, j}; } } } return new int[2]; } }
|
结果当然是对的,但是耗时有点长,下面看了看官方给的解答。
优秀题解
两遍 Hash 表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); } }
|
这个题解还是比较容易看懂的,就是使用了 HashMap 来代替了查找第二个数字的内层循环,把时间复杂度从 O(n ^ 2) 降到了 O(n)。
但是这种解法和我的解法在有些测试样例下会输出不同的结果(都是正确的),比如对于以下样例:
1 2
| nums = [1, 2, 2, 3] target = 3
|
我的解法得到的答案是:[0, 1]
而这种方法得到的应该是:[0, 2]
原因应该是在向 HashMap 中放入 key 重复的元素时,会覆盖之前的元素,所以会使用最后出现的数字;而我的解法中是从前向后遍历的,所以会直接使用第一次遇到的数字。
一遍 Hash 表
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } }
|
这个题解的思路更巧妙,最多只遍历了一次数组,因此时间复杂度也是 O(n)。