LeetCode每日一题(354. Russian Doll Envelopes)

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope’s width and height.

Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

Note: You cannot rotate an envelope.

Example 1:

Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3

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

Example 2:

Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1

Constraints:

  • 1 <= envelopes.length <= 105
  • envelopes[i].length == 2
  • 1 <= wi, hi <= 105

  1. 按照 width 递增排序, 如果 widht 相同则按 height 递减排序
  2. 找到 height 的 LIS(longest increasing subsequence)

impl Solution {
    pub fn max_envelopes(mut envelopes: Vec<Vec<i32>>) -> i32 {
        envelopes.sort_by(|p1, p2| {
            if p1[0] == p2[0] {
                return p2[1].cmp(&p1[1]);
            }
            p1[0].cmp(&p2[0])
        });
        let mut sub = Vec::new();
        for envelope in envelopes {
            if let Some(last) = sub.last() {
                if &envelope[1] > last {
                    sub.push(envelope[1]);
                    continue;
                }
                let i = sub.iter().position(|v| v >= &envelope[1]).unwrap();
                sub[i] = envelope[1];
                continue;
            }
            sub.push(envelope[1]);
        }
        sub.len() as i32
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值