[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;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值