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

      

  • 相关阅读:
    在图像中随机更改像素值程序——matlab
    图像频谱图画图——matlab
    图像三维灰度分布图——matlab
    JVM安全退出(如何优雅的关闭java服务)
    annotation(@Retention@Target)详解
    synchronized与static synchronized 的区别
    ExecutorService对象的shutdown()和shutdownNow()的区别
    execute和submit的区别
    Java线程之FutureTask与Future浅析
    Runnable与Callable
  • 原文地址:https://www.cnblogs.com/parapax/p/3637483.html
Copyright © 2020-2023  润新知