[leetcode] 354. Russian Doll Envelopes

Russian Doll Envelopes

描述

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

Example:

Given envelopes = [[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).

我的代碼

俄國沙皇問題
1.排序策略:假定二元組記爲(a,b),先對a升序排列,當a相同時對b降序排列;
2.排序後只用看b, b的最長不降子序列就是最終的結果;
3.維持一個有效區ends,ends[i]記錄b中長度爲i+1的最長不降子序列的最小末尾;
注意:在本題中,當拿出的b中的值與ends中的某個值相等時,應該將其放入ends中與其相等的值的位置處,故這個時候應該更新r而不是l。
(更多見算法學習中的筆記)

class Solution {
public:

   #define max(a,b) a>b?a:b 

    static bool cmp(pair<int, int> env1, pair<int, int> env2)
    {
        if (env1.first!= env2.first)
            return env1.first<env2.first;
        else
            return env1.second > env2.second;
    }

    int maxEnvelopes(vector<pair<int, int> >& envelopes) {
        if (envelopes.empty())
        {
            return 0;
        }
        else
        {
             sort(envelopes.begin(), envelopes.end(), cmp);
             int len=envelopes.size();
             vector<int> ends;
             ends.resize(len);
             ends[0]=envelopes[0].second;
             int l=0, r=0;
             int Right=0;
             for (int i=1; i<len; i++)
             {
                l=0;
                r=Right;
                while(l<=r)
                {
                    int ind=(l+r)/2;    
                    if (envelopes[i].second > ends[ind])
                    {
                        l=ind+1;
                    }
                    else
                    {
                        r=ind-1;
                    }
                }
                Right=max(Right,l);
                ends[l]=envelopes[i].second;
             }
             return Right+1;
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章