zoukankan      html  css  js  c++  java
  • 3Sum

    Question:

    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 class Solution {
     2 public:
     3     vector<vector<int>> threeSum(vector<int>& nums) {
     4     vector< vector<int> > result;
     5     if(nums.size()<3)
     6         return result;
     7     sort(nums.begin(),nums.end());
     8     const int target=0;
     9     auto last=nums.end();
    10     for(auto i=nums.begin();i<last-2;i++)
    11     {
    12         auto j=i+1;
    13         if(i>nums.begin() && *i==*(i-1)) continue;
    14         auto k=last-1;
    15         while(j<k)
    16         {
    17             if(*i+*j+*k<target)
    18                 {j++;while(*j==*(j-1) && j<k) ++j;}
    19             else if(*i+*j+*k>target)
    20                 {k--;while(*k==*(k+1) && j<k) --k;}
    21             else
    22             {
    23                 vector<int> x;
    24                 x.push_back(*i);
    25                 x.push_back(*j);
    26                 x.push_back(*k);
    27                 result.push_back(x);
    28                 ++j;
    29                 --k;
    30                 while(*j==*(j-1) && *k==*(k+1) && j<k) ++j;
    31             }
    32         }
    33     }
    34     return result;
    35     }
    36 };

    
    
  • 相关阅读:
    用Python获取Linux资源信息的三种方法
    对python中元类的理解
    一道有趣的和编程无关的编程题思考
    Python编程进阶
    函数计算的 Python手册小问题
    Linux 命令
    pyechart
    KV数据库Redis
    微博API 学习记录
    非阻塞式的 requests.post 学习
  • 原文地址:https://www.cnblogs.com/riden/p/4631460.html
Copyright © 2011-2022 走看看