例题:Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
一、思路最简单的算法就是遍历,时间复杂度会很高,为O(N*N*N)
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
List<Integer> inlist;
List<List<Integer>> outlist = new ArrayList<List<Integer>>();
for(int i=0;i<len-2;i++){
for(int j=i+1;j<len-1;j++){
for(int k=j+1;k<len;k++){
if(nums[i]+nums[j]+nums[k]==0){
inlist = new ArrayList<Integer>();
inlist.add(nums[i]);
inlist.add(nums[j]);
inlist.add(nums[k]);
Collections.sort(inlist);
if(!outlist.contains(inlist))
outlist.add(inlist);
}
}
}
}
return outlist;
}
}
二、降低时间复杂度到O
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
Arrays.sort(nums);//首先排序
List<List<Integer>> outlist = new ArrayList<List<Integer>>();
for(int i=0;i<len-2;i++){
while(i>0 && nums[i]==nums[i-1] && i<len-2)//跳过相同的元素
i = i+1;
int j= i+1;
int k = len-1;
while(j<k){
if(nums[i]+nums[j]+nums[k] == 0)
outlist.add(Arrays.asList(nums[i], nums[j], nums[k]));
j++;
k--;
while(nums[j]==nums[j-1] && j<k){ //跳过相同的元素
j++;
}
while(nums[k]==nums[k+1] && j<k){ //跳过相同的元素
k--;
}
}
else if(nums[i]+nums[j]+nums[k] > 0){
k--;
}
else{
j++;
}
}
}
return outlist;
}
}