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.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list=new ArrayList();
List<List<Integer>> resList=new ArrayList();
Set set = new HashSet();
int i,j,k;
for(i=0;i<nums.length;i++){
for(j=i+1;j<nums.length;j++){
for(k=j+1;k<nums.length;k++){
if(nums[i]+nums[j]+nums[k]==0){
List<Integer> sList=new ArrayList();
sList.add(nums[i]);
sList.add(nums[j]);
sList.add(nums[k]);
list.add(sList);
}
}
}
}
for(List<Integer> iList:list){
if(set.add(iList)){
resList.add(iList);
}
}
return resList;
}
}
逻辑没写错,只不过是这道题时间有限时,我写的算法超出了运行时间,说明不够优化。