标签:
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: 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) { Arrays.sort(nums); List<List<Integer>> res=new ArrayList<List<Integer>>(); for(int i=0;i<nums.length;i++) { if(i!=0&&nums[i]==nums[i-1]) { continue; } for(int j=i+1,k=nums.length-1;j<k;) { int sum=nums[i]+nums[j]+nums[k]; if(sum==0) { List<Integer> combination=new ArrayList<Integer>(); combination.add(nums[i]); combination.add(nums[j]); combination.add(nums[k]); res.add(combination); j++; k--; while(nums[j]==nums[j-1]&&nums[k]==nums[k+1]&j<k) { j++; k--; } } else if(sum<0) { j++; while(nums[j]==nums[j-1]&&j<k) { j++; } } else { k--; while(nums[k]==nums[k+1]&&k>j) { k--; } } } } return res; } }
标签:
原文地址:http://www.cnblogs.com/Machelsky/p/5858649.html