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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
/*
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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
*/
注意去重
public class sum3 {
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
void add(int value){
if(map.containsKey(value)){
map.put(value,map.get(value)+1);
}
else{
map.put(value,1);
}
}
public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
if(num==null)
return res;
//先排序
Arrays.sort(num);
for(int i=0;i<num.length-2;i++){
if(num[i]>0)
break;
//再选两个数
int left=i+1;
int right=num.length-1;
int target=0-num[i];
//避免重复
if(i>0&&num[i]==num[i-1]){
continue;
}
while(left<right){
if(num[left]+num[right]==target){
ArrayList<Integer> temp=new ArrayList<>();
temp.add(num[i]);
temp.add(num[left]);
temp.add(num[right]); //一个solution
res.add(temp);
left++;
right--;
//防止重复
while (left<right&&num[left]==num[left-1]){
++left;
}
while (left<right&&num[right]==num[right+1]){
--right;
}
}
else if(num[left]+num[right]<target){
left++;
}
else {
right--;
}
}
}
return res;
}
public static void main(String[] args) {
sum3 sum=new sum3();
int[] s={-1,0,1,2,-1,-4};
ArrayList<ArrayList<Integer>> ans=sum.threeSum(s);
System.out.println(ans);
}
}
hashmap解法类似
链接:https://www.nowcoder.com/questionTerminal/345e2ed5f81d4017bbb8cc6055b0b711
来源:牛客网
class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> arrayLists = new ArrayList<List<Integer>>();
Arrays.sort(num);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(num.length); //用hashmap方便查找
for(int i=0;i<num.length;i++){ //放入到hashmap中
map.put(num[i],i);
}
for(int i=0;i<num.length;i++){
if(i>0&&num[i]==num[i-1]){ //每次第一个数挑选一个不同的数
continue;
}
if(num[i]>0){ //剪枝
return arrayLists;
}
for(int j=i+1;j<num.length;j++){
if(num[j]==num[j-1]&&j-i>1){ //排除第二数和第一个数重复很多遍 例如:-1 -1 -1 ,只需要第一个和第二相加就可以,第三个可以忽略
continue;
}
if(num[i]+num[j]>0){
break;
}
int temp = -(num[i] + num[j]);
if(map.containsKey(temp)&&map.get(temp)>j){ //保证三个数依次递增,这样可以不重复
ArrayList<Integer> arrayList =new ArrayList<Integer>();
arrayList.add(num[i]);
arrayList.add(num[j]);
arrayList.add(temp);
arrayLists.add(arrayList);
}
}
}
return arrayLists;
}