• LeetCode 3Sum


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

    枚举第一个数,然后在其后的数组设置两个指针。O(n^2)

     1 class Solution {
     2 private:
     3     vector<vector<int> > ret;
     4 public:
     5     vector<vector<int> > threeSum(vector<int> &num) {
     6         // Start typing your C/C++ solution below
     7         // DO NOT write int main() function
     8         ret.clear();
     9         sort(num.begin(), num.end());
    10         
    11         for(int i = 0; i < num.size(); i++)
    12         {
    13             if (i > 0 && num[i] == num[i-1])
    14                 continue;
    15                 
    16             int j = i + 1;
    17             int k = num.size() - 1;
    18             
    19             while(j < k)
    20             {
    21                 if (j > i + 1 && num[j] == num[j-1])
    22                 {
    23                     j++;
    24                     continue;
    25                 }
    26                 
    27                 if (k < num.size() - 1 && num[k] == num[k+1])
    28                 {
    29                     k--;
    30                     continue;
    31                 }
    32                 
    33                 int sum = num[i] + num[j] + num[k];
    34                 
    35                 if (sum == 0)
    36                 {
    37                     vector<int> a;
    38                     a.push_back(num[i]);
    39                     a.push_back(num[j]);
    40                     a.push_back(num[k]);
    41                     ret.push_back(a);
    42                     j++;
    43                 }
    44                 else if (sum < 0)
    45                 {
    46                     j++;
    47                 }
    48                 else
    49                 {
    50                     k--;
    51                 }
    52             }
    53         }
    54         
    55         return ret;
    56     }
    57 };
  • 相关阅读:
    Kubernetes基础:Pod的详细介绍
    十分钟带你理解Kubernetes核心概念
    kubectl命令行工具用法详解
    GDPR给安全的影响
    开源软件会被云杀死吗 ?
    VMware前路难测,多个厂家群雄逐鹿
    如何实现linux+windows双系统启动
    IT行业——Linux
    i3 窗口管理器使 Linux 更美好
    在 Linux 中使用超级用户权限
  • 原文地址:https://www.cnblogs.com/chkkch/p/2742707.html
Copyright © 2020-2023  润新知