标签:
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:
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 ArrayList<ArrayList<Integer>> threeSum(int[] num) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); if(num.length<3||num == null) return res; Arrays.sort(num); for(int i = 0; i <= num.length-3; i++){ if(i==0||num[i]!=num[i-1]){//remove dupicate 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> unit = new ArrayList<Integer>(); unit.add(num[i]); unit.add(num[low]); unit.add(num[high]); res.add(unit); low++; high--; while(low<high&&num[low]==num[low-1])//remove dupicate low++; while(low<high&&num[high]==num[high+1])//remove dupicate high--; }else if(sum > 0) high --; else low ++; } } } return res; } }
标签:
原文地址:http://www.cnblogs.com/hygeia/p/5469695.html