思路1:把数组从小到大排列,常规三重循环,但是它的时间复杂度是O(N3),leetcode判断会超时
思路2:把数组从小到大排列,我们定义数组三个位置:first,second,third。
第一层循环:first
第二层循环:second和third双向移动,分别在左侧和右侧依次靠近
因为a+b+c=0,我们无需在第二层循环中遍历N2(N的平方),只需要把第二层循环遍历一次,当second和third相遇,便结束循环。因此,时间复杂度为O(N2)。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len=nums.length;
Arrays.sort(nums);//给nums数组排序
List<List<Integer>> list1=new LinkedList<>();
for(int first=0;first<len;first++){
if(first>0&&nums[first]==nums[first-1]) continue;
int target=-nums[first];
int third=len-1;
for(int second=first+1;second<len;second++){
if(second>first+1&&nums[second]==nums[second-1]) continue;
while(second<third&&nums[second]+nums[third]>target){
third--;
}
if(second==third) break;
if(nums[first]+nums[second]+nums[third]==0){
List<Integer> list2=new LinkedList<>();
list2.add(nums[first]);
list2.add(nums[second]);
list2.add(nums[third]);
list1.add(list2);
}
}
}
return list1;
}
}