码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] 3Sum

时间:2014-11-01 06:12:01      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   for   sp   div   

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,需要跳过当前值。

[Leetcode] 3Sum

标签:des   style   blog   io   color   ar   for   sp   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4066302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!