3 sum
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)
首先给数组sort。
先固定一个数字, 然后在剩下的段里找另外两个数字使得他们的和等于第一个数字的相反数即可。 可以划归到2 sum。
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> threeSum(int[] num) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 Arrays.sort(num); 6 ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); 7 if(num.length < 3){ 8 return result; 9 } 10 for(int i = 0; i < num.length - 2; i ++){ 11 if(i - 1 > -1 && num[i] == num[i - 1]){ 12 //必须得先判i- 1 > -1 要不会因不存在num[-1]报错 13 continue; 14 } 15 int sum = -num[i]; 16 int header = i + 1; 17 int tail = num.length - 1; 18 while(header < tail){ 19 if(num[header] + num[tail] > sum){ 20 tail --; 21 } 22 else if(num[header] + num[tail] < sum){ 23 header ++; 24 } 25 else{ 26 ArrayList<Integer> item = new ArrayList<Integer>(); 27 item.add(num[i]); 28 item.add(num[header]); 29 item.add(num[tail]); 30 if(!result.contains(item)){ 31 result.add(item); 32 } 33 tail --; 34 header ++; 35 } 36 } 37 } 38 return result; 39 } 40 }
posted on 2013-04-17 13:20 Step-BY-Step 阅读(181) 评论(0) 编辑 收藏 举报