3Sum
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:
- 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)
Idea: o(n^2) solution exists. First sort the array, and then from left to right, for each num[i], search the pair that sums up to -num[i] using Two Sum algorithm.
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> threeSum(int[] num) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 Arrays.sort(num); 5 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 6 if(num == null || num.length < 3) return result; 7 int len = num.length; 8 for(int i = 0; i < num.length-2; i ++){ 9 if(i==0 || num[i]>num[i-1]){ 10 int j = i + 1; 11 int h = len - 1; 12 while(j < h){ 13 int sum = 0 - num[j] - num[h]; 14 if(sum == num[i]){ 15 ArrayList<Integer> row = new ArrayList<Integer>(); 16 row.add(num[i]); 17 row.add(num[j]); 18 row.add(num[h]); 19 result.add(row); 20 h--; 21 j++; 22 while(h>j && num[h]==num[h+1]) h--; 23 24 while(j<h && num[j]==num[j-1]) j++; 25 }else if(sum < num[i]){ 26 h --; 27 }else if(sum > num[i]){ 28 j ++; 29 } 30 } 31 } 32 } 33 return result; 34 } 35 }
第二遍:
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> threeSum(int[] num) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 5 if(num == null || num.length < 3) return result; 6 Arrays.sort(num); 7 for(int i = 0; i < num.length - 2; i ++){ 8 if(i == 0 || num[i] > num[i-1]){ 9 int target = - num[i]; 10 int j = i + 1; 11 int h = num.length - 1; 12 while(j < h){ 13 if(num[j] + num[h] == target){ 14 ArrayList<Integer> row = new ArrayList<Integer>(); 15 row.add(num[i]); 16 row.add(num[j]); 17 row.add(num[h]); 18 result.add(row); 19 int jnum = num[j]; 20 int hnum = num[h]; 21 while(num[j] == jnum && j < h) j ++; 22 while(num[h] == hnum && h > j) h --; 23 }else if(num[j] + num[h] > target){ 24 h --; 25 }else{ 26 j ++; 27 } 28 } 29 } 30 } 31 return result; 32 } 33 }
posted on 2013-10-16 13:45 Step-BY-Step 阅读(148) 评论(0) 编辑 收藏 举报