[Leetcode] 3Sum

Given an array S of n integers, are there elements abc 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)

 

Solution:

 1 public class Solution {
 2     public List<List<Integer>> threeSum(int[] num) {
 3         List<List<Integer>> result = new ArrayList<List<Integer>>();
 4         if (num.length < 3)
 5             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                 continue;
10             int a = num[i];
11             int low = i + 1;
12             int high = num.length - 1;
13             while (low < high) {
14                 if (-a == num[low] + num[high]) {
15                     List<Integer> temp = new ArrayList<Integer>();
16                     temp.add(a);
17                     temp.add(num[low]);
18                     temp.add(num[high]);
19                     result.add(temp);
20                     low++;
21                     high--;
22                     while (low < high && num[low] == num[low - 1])
23                         low++;
24                     while (low < high && num[high] == num[high + 1])
25                         high--;
26                 } else if (-a > num[low] + num[high])
27                     low++;
28                 else
29                     high--;
30             }
31         }
32         return result;
33     }
34 }

注意:如果current value==previous value,需要跳过当前值。

posted @ 2014-11-01 01:02  Phoebe815  阅读(138)  评论(0编辑  收藏  举报