Mixture

身未动,心已远

导航

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.

  

posted on 2014-04-01 05:17  parapax  阅读(312)  评论(0编辑  收藏  举报