zoukankan      html  css  js  c++  java
  • STL: vector range constructor, set::insert

    思路来自https://github.com/soulmachine/leetcode,是4Sum这道题

    class Solution {
    public:
        vector<vector<int> > fourSum(vector<int> &num, int target) {
            vector<vector<int> > res;
            if(num.size()<4)
                return res;
            unordered_map<int, vector<pair<int,int> > > twoSumBuf;
            sort(num.begin(),num.end());
            for(int i=0;i<num.size()-1;i++) {
                for(int j=i+1;j<num.size();j++) {
                    twoSumBuf[num[i]+num[j]].push_back(pair<int,int>(i,j));
                }
            }
            set<vector<int> > setRes;
            for(size_t c = 2;c<num.size()-1;c++) {
                for(size_t d = c+1;d<num.size();d++) {
                    int left = target-num[c]-num[d];
                    if(twoSumBuf.find(left)!=twoSumBuf.end()) {
                        for(int index =0;index<twoSumBuf[left].size();index++) {
                            int indexA = twoSumBuf[left][index].first;
                            int indexB = twoSumBuf[left][index].second;
                            if(c<=indexB)
                                continue;
                            setRes.insert(vector<int>{num[indexA],num[indexB],num[c],num[d]});
                        }
                    }
                }
            }
            return vector<vector<int> >(setRes.begin(),setRes.end());
        }
    };

    有两个不太熟悉的地方,一个是vector容器的Range constructor:

    template <class InputIterator>
             vector (InputIterator first, InputIterator last,
                     const allocator_type& alloc = allocator_type());

    Constructs a container with as many elements as the range [first,last), with each element constructed from its corresponding element in that range, in the same order.

    所以vector<vector<int> >(setRes.begin(),setRes.end())就通过set的range构造出了一个vector.

    然后是set::insert,因为set中的元素都是unique的,所以在使用pair<iterator,bool> insert (const value_type& val)函数的时候,只有在set中不含当前元素的时候才能成功插入。

    返回值的说明如下:

    The single element versions (1) return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.

      

  • 相关阅读:
    (转)c++中NULL与nullptr的区别
    剑指offer:面试题1:赋值运算符函数
    剑指offer开篇
    立flag
    牛客网程序员面试金典:1.2——原串翻转(java实现)
    牛客网程序员面试金典:1.1确定字符互异(java实现)
    剑指Offer:面试题34——丑数(java实现)
    剑指Offer:面试题33——把数组排成最小的数(java实现)(未完待续)
    剑指Offer:面试题32——从1到n整数中1出现的次数(java实现)
    8种网站防盗链手段
  • 原文地址:https://www.cnblogs.com/parapax/p/3637483.html
Copyright © 2011-2022 走看看