目录
一、题目描述
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6 输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6 输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2)
的算法吗?
二、解答
1)方法一(暴力)
想法很简单,同过双循环遍历列表,找出相应答案,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
return new int[] {i, j};
}
}
}
return new int[] {};
}
}
算法运行时间是O(n^2) 。运行效果如下:
击败8%,还能优化。
2)方法二(使用哈希表)
方法一纯粹的是双循环遍历一个列表, 那第内层循环可以去掉吗?想一想,算法中常用的伎俩空间换时间,如果我能知道target - num[i]是不是存在,那就可以去掉内存循环了。
目标为target,当前值为nums[i],要找到一个x使得x + nums[i] = target,其实就是x = target - nums[i],如果我能知道target - nums[i]的值是否存储也就解决了当前问题。没错,我们可以使用Map来达到目的,key 为当前值nums[i],value为当前值的索引i。
每当遍历一个元素的时候就判断nums[i]在不在map里面,如果不在就加入map,同时判断target - nums[i]是不是在map里面,如果在则说明已经找到答案,即{i, (target - nums[i])的数组索引},代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (null == map.get(nums[i])) {
map.put(nums[i], i);
}
int num = target - nums[i];
Integer numIndex = map.get(num);
if (null != numIndex && i != numIndex) {
return new int[] {i, numIndex};
}
}
return new int[] {};
}
}
运行效果如下:
击败99.64%,性能大幅提升了啊。
还有没有更好的方法呢?leetcode里面查看了其他解法发现了一种比较巧妙的解法。
3)方法三(有条件的双循环)
这里的双循环与方法一的双循环有所区别,先直接看代码吧:
class Solution {
public int[] twoSum(int[] nums, int target) {
if (null == nums || 0 == nums.length) {
return new int[] {};
}
int lastIndex = nums.length - 1;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (target == nums[i] + nums[j]) {
return new int[] {i, j};
}
if (target == nums[lastIndex - i] + nums[lastIndex - j]) {
return new int[] {lastIndex - i, lastIndex - j};
}
}
}
return new int[] {};
}
}
在内存循环中迭代查看i, j的同时,顺便看了下lastIndex - i, lastIndex - j是否就是想要的答案,那这种方式会不会有遗漏呢?这里通过一个例子说明下。
有5个数,其下标为0 1 2 3 4,按照常规双循环迭代遍历的顺序如下:
0 1 t1
0 2 t1
0 3 t1
0 4 t1
1 2 t2
1 3 t2
1 4 t1
2 3 t2
2 4 t1
3 4 t1
按照这里的迭代顺序如下:
0 1 -> 4 3
0 2 -> 4 2
0 3 -> 4 1
0 4 -> 4 0
1 2 -> 3 2
1 3 -> 3 1
1 4 -> 3 0
2 3 -> 2 1
2 4 -> 2 0
3 4 -> 1 0
我在常规迭代的右边标出了外层循环的次数,t1表示在第一次外层循环遍历到该对元素,t2表示第二次外层循环遍历到该对元素。通过这个例子发现并不完全需要O(n^2)就能遍历完所有的数据对。
该方法的运行效果也很逆天,击败100%