zoukankan      html  css  js  c++  java
  • LeetCode_三数之和

    #include<iostream>
    #include <vector>
    #include <set>
    #include <functional>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string>
    #include <sstream>
    #include <list>
    #include <map>
    #include <stack>
    #include <algorithm>
    //#include <iterator>
    using namespace std;
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    
    vector<vector<int>> threeSum(vector<int>& nums) {
        int length = nums.size();
        if (length < 3)
            return vector<vector<int>>();
        int pa = 0, pb = 1, pc = length - 1;
        sort(nums.begin(), nums.end(), [](const int &a, const int &b){return a < b; });
    
        vector<vector<int>> result;
        for (int pa = 0; pa < length - 2; pa++)
        {
            pb = pa + 1;
            pc = length - 1;
            int value = -nums[pa];
            while (pb < pc)
            {
                if (nums[pb] + nums[pc] > value)
                    pc--;
                else if (nums[pb] + nums[pc] < value)
                    pb++;
                else
                {
                    result.push_back({ nums[pa], nums[pb], nums[pc] });
                    while (nums[pb] == nums[pb+1])
                        pb++;
                    while (nums[pc] == nums[pc - 1])
                        pc--;
                    pb++;
                    pc--;
                }
            }
        }
        sort(result.begin(), result.end());
        auto end = unique(result.begin(), result.end());
        result.erase(end, result.end());
        return result;
    }
    //void unique(vector<vector<int>> &group)
    //{
    //
    //}
    int main()
    {
        vector<int> vi = { -4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6 };
        vector<vector<int>> result = threeSum(vi);
    
        for (auto v : result)
        {
            for (auto i : v)
                cout << i << " ";
            cout << endl;
        }
    
    
        return 0;
    }

    正常需要o(n^3)复杂度,可采用先固定第一位,然后后两位用游标的方式,复杂度(n^2)

  • 相关阅读:
    excel VBA构造正则函数(双参数)
    excel VBA构造函数就是这么简单
    excel VBA中正则模块vbscript.regexp的用法
    excel VBA构造正则函数(单参数)
    USB 设备插拔事件处理
    MySQL 修改 root 密码命令
    函数指针
    串口编程需要注意的地方
    写开机自启动程序应该注意的一点
    C++ 中 delete 和 delete[] 的区别
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9039377.html
Copyright © 2011-2022 走看看