Note:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
Subscribe to see which companies asked this question
public class Solution { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(num == null || num.length<3) return result; Arrays.sort(num); for(int first = 0;first<num.length-2;++first) { if(first > 0 && num[first]==num[first-1]) continue; if(num[first]>0) break; int second = first+1; int third = num.length -1; while(second<third) { int sum = num[first]+num[second]+num[third]; if(sum == 0) { List<Integer> l = new ArrayList<Integer>(); l.add(num[first]); l.add(num[second]); l.add(num[third]); result.add(l); while(++second<third && num[second]==num[second-1]); while(second<--third && num[third]==num[third+1]); } else if(sum>0) while(second<--third && num[third]==num[third+1]); else while(++second<third && num[second]==num[second-1]); } } return result; } }
原文:http://www.cnblogs.com/neweracoding/p/5264095.html