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不动的情况下,