• 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)

  • 相关阅读:
    dotnet logging serilog support
    普通索引和唯一索引,应该怎么选择?
    怎么减少行锁对性能的影响?
    全局锁和表锁 :给表加个字段怎么有这么多阻碍?
    Python调用函数模板
    Shell语言开发基础模板
    Python语言开发小工具库
    笔记day02
    笔记day06
    第2周需求
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9039377.html
Copyright © 2020-2023  润新知