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,最容易想到的方法就是直接暴力三层循环,但这个就是来搞笑的,O(N3)
然后很容易想到的就是先排序,从小到大排序后,这样就可以利用大小关系来筛选掉一些,然后再遍历
我想了想,发现复杂度并没有改变,因为重排后我还是三层遍历了,所以不行
然后我就没继续想了,直接看discussion了,结果发现排名第一的java答案跟我想的差不多,多想的那步是由于排序后,我们取第i个a和第i+1个b和第nums.length-1个元素c,如果存在a+b+c==0,那么势必下一个满足三元式的解,b要往右移动,c要往左移动,因为c是最右边的元素,它是最大的,在a不动的情况下,它移动那么b也必须得往又移动,不然不会满足等式
这样就变成了双层循环,O(N2),而排序用的是快排,O(NlogN),所以最终复杂度O(n2)
代码:
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new LinkedList<>();
for(int i=0;i< nums.length-2;i++){
int lo = i+1;int hi = nums.length-1;
if(i==0||i>0&&nums[i]!=nums[i-1]){
while(lo<hi) {
if (nums[lo] + nums[hi] + nums[i] == 0) {
res.add(Arrays.asList(nums[i],nums[lo],nums[hi]));
while (lo<hi&&nums[hi] == nums[hi - 1]) hi--;
while (lo<hi&&nums[lo] == nums[lo + 1]) lo++;
hi--;lo++;
}
else if(nums[lo]+nums[hi]+nums[i]>0){
hi--;
}
else{
lo++;
}
}
}
}
return res;
}
}