zoukankan      html  css  js  c++  java
  • LeetCode: 3Sum

    Title: 

    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)


    //68ms
    class Solution {
    public:
        vector<vector<int> > threeSum(vector<int> &num) {
            std::sort(num.begin(), num.end());
            int target1 = 0;
            vector<int> every_vec;
            vector<vector<int> > final_vec;
            if (num.size() <= 2) return final_vec; //corner case:
            for (int i = 0; i < num.size() - 2; ++i) {
                if(i > 0 && num[i] == num[i - 1]) 
                    continue;
                target1 = 0 - num[i];
                int first = i + 1;
                int last = num.size() - 1;
                while (first < last) {
                    if (num[first] + num[last] < target1) {
                        while (first < num.size() - 1 && num[first] == num[first + 1]) first++;
                        first++;
                    }else if (num[first] + num[last] > target1) {
                        while (last > 0 && num[last] == num[last - 1]) last--;
                        last--;
                    }else {
                        every_vec.clear();
                        every_vec.push_back(num[i]);
                        every_vec.push_back(num[first]);
                        every_vec.push_back(num[last]);
                        final_vec.push_back(every_vec);
                        while (first < num.size() - 1 && num[first] == num[first+1]) first++;
                        while (last > 0 && num[last] == num[last - 1]) last--;
                        first++;
                        last--;
                    }
                }
            }
            return final_vec;
        }
    };
  • 相关阅读:
    Excel宏开发之合并单元格
    excel破解工作簿与工作表保护
    jquery高级编程学习
    Git 和 SVN 存储方式的差异对比
    SSH 连接时间超时
    linux 使用 Python 画图工具matplotlib 提示display 错误
    centos安装字体
    linux编译安装中configure、make和make install各自的作用
    npm run build
    centos ssh 免密码登录
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4419191.html
Copyright © 2011-2022 走看看