https://leetcode-cn.com/problems/3sum/
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets(三个一组) in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
分析题目:给定一个整数数组,结果返回无重复且和为0的三元组;
首先想到的就是三层循环,简单暴力,先考虑一下重复问题:
1、元素重复但所在位置不同,如三元组(a,b,c),取该类型时,形如(b,a,c)、(c,a,b)则不可取,考虑排序,有 a<=b<=c,保证了只有(a,b,c)这个顺序会被枚举到;
2、完全重复,对于每一重循环而言,相邻两次枚举的元素相同,会造成重复,如:[0,1,2,2,2,3]在第三层循环会多次取2对比 ,[0,0,0,1,2,3]在第一层会多次取0对比(实际只需要取一次就行了),需要将循环「跳到」下一个不相同的元素;
代码如下:
public List> threeSum(int[] nums) {
int length = nums.length;
Arrays.sort(nums);
List> result = new ArrayList>();
for(int i = 0; i < length; i++){
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for(int j = i + 1; j < length; j++){
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
for(int k = j +1; k < length; k++){
if (k > j + 1 && nums[k] == nums[k - 1]) {
continue;
}
if(nums[i]+nums[j]+nums[k] == 0){
result.add(Arrays.asList(nums[i],nums[j],nums[k]));
}
}
}
}
return result;
}
然而现实是残酷的:
太过暴力也不好,三层for循环所带来O(n^3)的时间复杂度,n稍大一点就会导致超时;
优化方案:三指针(双指针),由a+b+c=0 -> a不变,将b,c作为一个整体a+(b+c)=0,b增大时(指针右移),为保持等式成立,c需要减小(指针左移);b初始下标为a下标+1,c初始下标为数组长度-1;b从左往右移,c从右往左移;直到b、c相遇时截止(保证b指针在c指针左侧);
双指针的方法,将枚举的时间复杂度从 O(N^2)减少至O(N)。为什么是O(N) 呢?这是因为在枚举的过程每一步中,「左指针」会向右移动一个位置(也就是 b),而「右指针」会向左移动若干个位置,这个与数组的元素有关,但我们知道它一共会移动的位置数为 O(N)
int length = nums.length;
Arrays.sort(nums);
List> result = new ArrayList>();
for(int i = 0; i < length; i++){
//保证不重复取相同数字
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
//c指针初始指向数组的最右端,a值必定<=0
int k = length - 1;
int firstNum = nums[i];
for(int j = i + 1; j < length; j++){
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
//保证b指针在c指针的左侧
while (j < k && nums[j] + nums[k] > -firstNum ) {
--k;
}
//指针重合,结束
if (j == k) {
break;
}
if(nums[i]+nums[j]+nums[k] == 0){
result.add(Arrays.asList(nums[i],nums[j],nums[k]));
}
}
}
return result;
}
参考:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/