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

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

  • 相关阅读:
    python-禅
    学习思路(待完善)
    思考-想法-研究生
    五一前随笔
    监督学习,非监督学习和半监督学习
    第二章maven的安装和配置
    maven实战 第一章
    常用接口测试工具
    jmeter监控服务器性能(转载)
    数据库操作
  • 原文地址:https://www.cnblogs.com/dengeven/p/3604901.html
Copyright © 2011-2022 走看看