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)

     1 class Solution {
     2 public:
     3     vector<vector<int> > threeSum(vector<int> &num) {
     4         vector<vector<int>> result;
     5         if (num.size() < 3) return result;
     6         sort(num.begin(), num.end());
     7         for (size_t i = 0; i < num.size() - 2; ++i) {
     8             if (i > 0 && num[i] == num[i - 1]) continue;
     9             size_t j = i + 1, k = num.size() - 1;
    10             while (j < k) {
    11                 if (j > i + 1 && num[j] == num[j - 1]) {
    12                     ++j;
    13                     continue;
    14                 }
    15                 if (k < num.size() - 1 && num[k] == num[k + 1]) {
    16                     --k;
    17                     continue;
    18                 }
    19                 int sum = num[i] + num[j] + num[k];
    20                 if (sum == 0) {
    21                     result.push_back({num[i], num[j], num[k]});
    22                     ++j;
    23                     --k;
    24                 } else if (sum < 0) {
    25                     ++j;
    26                 } else {
    27                     --k;
    28                 }
    29             }
    30         }
    31         return result;
    32     }
    33 };
    View Code

    先排序,再左右夹逼查找。输出要求不重复,所以需要进行一些剪枝处理。

  • 相关阅读:
    Linux文件系统
    Linux用户和用户管理
    Linux磁盘管理
    vi编辑器
    Linux常用命令
    Linux进程管理
    servlet运行过程
    http的get和post方法的区别
    千元机小荐
    JavaScript 正则表达式(Reg Exp)
  • 原文地址:https://www.cnblogs.com/dengeven/p/3604901.html
Copyright © 2011-2022 走看看