分析:
有人相爱,有人夜里开车看海,有人leetcode第一题都做不出来。——力扣开篇
这道题主要有三种方法:暴力循环、字典映射、双指针
两数之和的数学意义为:
a
+
b
=
c
a+b=c
a+b=c,亦可以表示为
a
=
c
−
b
a=c-b
a=c−b,那么当前遍历到的数即为b,通过查看从头到当前b的这段范围内是否有a,来看能不能找到两个数的和。
暴力循环 O ( n 2 ) O(n^2) O(n2)
第一层循环 i i i枚举整型数组中的每一个数,第二层循环 j j j枚举从数组起始位置到 n u m s [ i ] nums[i] nums[i]的每一个数,当发现 n u m s [ j ] + n u m s [ i ] = = t a r g e t nums[j]+nums[i]==target nums[j]+nums[i]==target时输出下标即可,此时注意输出的是 [ j , i ] [j,i] [j,i]。有两个循环,因此时间复杂度是 O ( n 2 ) O(n^2) O(n2)。
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
for (let i = 0; i < nums.length; i ++) {
for (let j = 0; j < i; j ++) {
if (nums[i] + nums[j] == target) return [j, i];
}
}
return [];
};
字典映射 O ( n ) O(n) O(n)
另一种方法可以使用哈希表,只需要遍历一遍 n u m s nums nums数组,在循环当中的每一步进行如下操作:
- 判断从 n u m s [ 0 ] − n u m s [ i − 1 ] nums[0]-nums[i-1] nums[0]−nums[i−1]有没有满足 t a r g e t − n u m s [ i ] target-nums[i] target−nums[i]的。如果有,则输出满足的元素的下标和 i i i。
- 如果没有满足条件的元素,则将 n u m s [ i ] nums[i] nums[i]和 i i i插入哈希表中,继续向后扫描。
双指针 O ( n l o g n ) O(nlogn) O(nlogn)
双指针算法思想很简单,但是在实现上会有一些问题,当我们对原数组进行排序后(双指针要求有序),找到答案后返回的是下标也是随着并不是原序列的下标。这就需要将值和下标成对存储,并且按照值进行排序。
代码——双指针——O(nlogn)+O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
// 创建一个包含原始索引的数组
int[][] numWithIndex = new int[nums.length][2];
for (int i = 0; i < nums.length; i++) {
numWithIndex[i][0] = nums[i];
numWithIndex[i][1] = i;
}
// 按值对数组进行排序
Arrays.sort(numWithIndex, (a, b) -> Integer.compare(a[0], b[0]));
// 使用双指针查找两个数的和为目标值
int l = 0, r = nums.length - 1;
while (l < r) {
int sum = numWithIndex[l][0] + numWithIndex[r][0];
if (sum == target) {
return new int[] {numWithIndex[l][1], numWithIndex[r][1]};
} else if (sum > target) {
r --;
} else {
l ++;
}
}
return null;
}
}
代码——哈希——O(n)+O(n)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < nums.length; i ++) {
int r = target - nums[i];
if (hash.containsKey(r)) return new int[] {hash.get(r), i};
hash.put(nums[i], i);
}
return null;
}
}