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

  • 相关阅读:
    LightOj1054
    LightOj1028
    Docker仓库(转载)
    Dockerfile(转载)
    Docker存储卷(转载)
    容器虚拟化网络和Docker容器网络(转载)
    Docker镜像管理基础(转载)
    Docker基础用法(转载)
    docker容器技术基础入门(转载)
    Redis 3种安装部署方式
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4066302.html
Copyright © 2011-2022 走看看