zoukankan      html  css  js  c++  java
  • LeetCode "4Sum"

    Similar strategy could be applied to 4Sum, as 2sum to 3sum, but that'll be O(n^3). Instead of 3 + 1, we can also divide it into 2 + 2. So the problem becomes finding another pair - yes hashmap.

    class Solution {
    public:
        struct Rec
        {
            Rec() : i0(0), i1(0) {}
            Rec(int ri0, int ri1) : i0(ri0), i1(ri1) {}
            bool equals(Rec &r)
            {
                return i0 == r.i0 || i1 == r.i1 || i0 == r.i1 || i1 == r.i0;
            }
            int i0;
            int i1;
        };
        vector<vector<int>> fourSum(vector<int> &num, int target) {        
            vector<vector<int>> ret;
            if(num.size() < 4) return ret;
    // Make pair size_t cnt = num.size(); unordered_map<int, vector<Rec>> hm; for (size_t i = 0; i < cnt - 1; i ++) for (size_t j = i + 1; j < cnt; j++) { int sum2 = num[i] + num[j]; if (hm.find(sum2) == hm.end()) { vector<Rec> v; v.push_back(Rec(i, j)); hm.insert(make_pair(sum2, v)); } else { hm[sum2].push_back(Rec(i, j)); } } //  Match unordered_set<string> done; auto it = hm.begin(); for (; it != hm.end(); it++) { int sum1 = it->first; auto it2 = hm.find(target - sum1); if (it2 != hm.end()) { for (int i = 0; i < it2->second.size(); i ++) for (int j = 0; j < it->second.size(); j ++) { Rec &r1 = it->second[j]; Rec &r2 = it2->second[i]; if (!r1.equals(r2)) { vector<int> cv; cv.push_back(num[r1.i0]); cv.push_back(num[r1.i1]); cv.push_back(num[r2.i0]); cv.push_back(num[r2.i1]); std::sort(cv.begin(), cv.end()); string str; for (int i = 0; i < cv.size(); i++) { str += std::to_string(cv[i]); } if (done.find(str) == done.end()) { ret.push_back(cv); done.insert(str); } } } } } return ret; } };
  • 相关阅读:
    java根据汉字获取全拼和首字母
    SQL 增加或删除一列
    C#实现WinForm传值实例解析
    C# 静态类与非静态类、静态成员的区别分析
    c# 面相对象1-概括
    c# 面相对象2-之封装性
    c# 面相对象3-之继承性
    面向对象基础知识(含义、修饰符、三大特性)
    c# 面相对象4-多态性
    用集合求平均分
  • 原文地址:https://www.cnblogs.com/tonix/p/3919254.html
Copyright © 2011-2022 走看看