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.
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
public int hashCode() {
int hashCode = 1;
for (E e : this)//E 为List<E>,this为需要添加的对象(String/ArrayList)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
HashSet<List<Integer>> set = new HashSet<List<Integer>>();
List<Integer> tmpList ;
for(int i = 0;i < nums.length; i++){
HashMap<Integer,Integer> map = new HashMap<>();
int target = 0 - nums[i];
for(int j = i+1; j < nums.length;j++){
int value = target - nums[j];
if(map.containsKey(value)){
tmpList = new ArrayList<Integer>();
tmpList.add(nums[i]);
tmpList.add(nums[j]);
tmpList.add(value);
Collections.sort(tmpList);
set.add(tmpList);
}else{
map.put(nums[j],j);
}
}
}
return new ArrayList<List<Integer>>(set);
}
}
由图可知效率不高。
学习到另外一种方式可以有效的降低时间复杂度。
首先先排序。
设置一个i,j,k,分别为不同的下标。i的值不能大于nums.length-2; j 的值不能大于nums.length-1, k的值不小于等于j
和之前一样,先固定i的值。之后nums[i],nums[j],nums[k]之和如果大于0,k--,反之j++,当j>=k时break;
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
HashSet<List<Integer>> set = new HashSet<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length-2;i++){
int j = i+1;
int k = nums.length-1;
while(j<k){
int sum =nums[i]+nums[j]+nums[k];
if(sum==0)
set.add(Arrays.asList(nums[i],nums[j++],nums[k--]));
else if(sum>0)
k--;
else if(sum<0)
j++;
}
}
return new ArrayList<List<Integer>>(set);
}
}
效率依旧不高,但是使用的方法可以借鉴。
3Sum Closest
4Sum
3Sum Smaller
原文:https://www.cnblogs.com/clnsx/p/12240564.html