zoukankan      html  css  js  c++  java
  • [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,需要跳过当前值。

  • 相关阅读:
    C++ P1890 gcd区间
    C++ P1372 又是毕业季I
    C++ CF822A I'm bored with life
    C++ P4057 [Code+#1]晨跑
    C++ CF119A Epic Game
    关于树状数组的几点总结
    markdown语法
    portal开发"下拉框"“日期框”查询要怎么配置
    泛型总结--待续
    Actioncontext跟ServletActionContext的区别---未完待续
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4066302.html
Copyright © 2011-2022 走看看