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] ]
code:
public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result=new ArrayList<>(); for(int i=0;i<nums.length-2;){ int target=-nums[i]; int front=i+1; int last=nums.length-1; while(front<last){ int sum=nums[front]+nums[last]; if(sum<target) front++; else if(sum>target) last--; else{ List<Integer> list=new ArrayList<>(); list.add(-target); list.add(nums[front]); list.add(nums[last]); result.add(list); front++; last--; while(front<last&&nums[front-1]==nums[front]) front++; while(last>front&&nums[last+1]==nums[last]) last--; } } i++; while (i < nums.length && nums[i] == nums[i-1]) i++; } return result; }