15. 3Sum
Medium
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
因为前面做过twosum的题,所以设法将3sum转化twosum来做。代码如下:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ret = new ArrayList<>();
Arrays.sort(nums);
//int med = (nums.length%2==0)?(nums.length/2-1):(nums.length/2);
if (nums == null || nums.length < 3)
return ret;
for(int i = 0; i<nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1] ) continue;
int low = i+1;
int high = nums.length-1;
int sum = 0-nums[i];
while(low<high){
if(nums[low]+nums[high]==sum){
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[low]);
list.add(nums[high]);
ret.add(list);
while(low<high && nums[low]==nums[low+1]) low++;
while(low<high && nums[high]==nums[high-1]) high--;
low++;high--;
}
else if(nums[low]+nums[high]<sum)
low++;
else high--;
}
}
return ret;
}
}
但上述程序在去重环节,操作较为复杂,所以我们引入HashMap来完成去重操作。
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] num) {
List<List<Integer>> res = new ArrayList<>();
if(num == null || num.length<3)
return res;
HashSet<ArrayList<Integer>> hs = new HashSet<ArrayList<Integer>>();
Arrays.sort(num);//千万不要丢排序的这个哦
for(int i=0;i<=num.length-3;i++){
int low = i+1;
int high = num.length-1;
while(low<high){
int sum = num[i]+num[low]+num[high];
if(sum==0){
ArrayList<Integer> util = new ArrayList<Integer>();
util.add(num[i]);
util.add(num[low]);
util.add(num[high]);
if(!hs.contains(util)){
hs.add(util);
res.add(util);
}
low++;
high--;
}else if(sum<0){
low++;
}else{
high--;
}
}
}
return res;
}
}
但是hashmap的运行时间较长为392ms 而单纯的判断语句只需77ms
此题选择解法一。