LintCode-三数之和

题目描述:

  给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

 注意事项

  在三元组(a, b, c),要求a <= b <= c。

  结果不能包含重复的三元组。

样例

  如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:

  (-1, 0, 1)

  (-1, -1, 2)

 1 public class Solution {
 2     /**
 3      * @param numbers : Give an array numbers of n integer
 4      * @return : Find all unique triplets in the array which gives the sum of zero.
 5      */
 6     public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
 7         ArrayList<ArrayList<Integer>>  result = new ArrayList<ArrayList<Integer>>();
 8         if(numbers == null || numbers.length<3)
 9             return result;
10         Arrays.sort(numbers);
11         for(int i = 0;i<numbers.length; i++){
12             int left = i+ 1;
13             int right = numbers.length - 1;
14             while(left < right){
15                 int sum = numbers[i] + numbers[left] + numbers[right];
16                 ArrayList<Integer> path = new ArrayList<Integer>();
17                 if(sum==0){
18                     path.add(numbers[i]);
19                     path.add(numbers[left]);
20                     path.add(numbers[right]);
21                     if(result.contains(path)==false)
22                         result.add(path);
23                     left++;
24                     right--;
25                 }else if(sum>0){
26                     right--;
27                 }else{
28                     left++;
29                 }
30             }
31         }
32        
33         return result;
34     }
35 }
原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5364692.html