15. 3Sum

时间:2023-03-08 22:08:17

Given an array S of n integers, are there elements abc 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 Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list1=new ArrayList<>();
List<Integer> list=new ArrayList<>();
Map<List<Integer>,List<Integer>> map=new HashMap<>();
int a=0; Arrays.sort(nums); for(int i=0;i<=nums.length-3;i++)
{
if(nums[i]<=0)
{
list.add(nums[i]);
a=nums[i]*(-1);
}
else break;
for(int j=i+1;j<=nums.length-2;j++)
{
if(nums[j]<=a)
{
list.add(nums[j]);
a=a-nums[j];
for(int k=j+1;k<=nums.length-1;k++)
{
if(nums[k]>a)
break;
else if(nums[k]==a)
{
list.add(nums[k]);
if(!map.containsKey(list))
{
map.put(list, list);
list1.add(list);
}
break;
} }
}
else break;
list=new ArrayList<>();
list.add(nums[i]);
a=nums[i]*(-1);
}
list=new ArrayList<>();
} return list1;
}
}