221 - 354 俄罗斯套娃信封问题

题目

给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

说明: 不允许旋转信封。

示例:

输入: envelopes = [[5,4],[6,4],[6,7],[2,3]] 输出: 3 解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。

解答

>

https://leetcode-cn.com/problems/russian-doll-envelopes/solution/zui-chang-di-zeng-zi-xu-lie-kuo-zhan-dao-er-wei-er/

这是一个非常取巧的方法

宽度升序排序,高度降序排序,然后在高度上,找最长递增子序列

1

https://leetcode-cn.com/problems/russian-doll-envelopes/solution/tan-xin-suan-fa-er-fen-cha-zhao-python-dai-ma-java/

来自李威威大佬的代码

class Solution:
    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        size = len(envelopes)
        if size < 2:
            return size
        envelopes.sort(key=lambda x: (x[0], -x[1]))
        tail = [envelopes[0][1]]
        for i in range(1, size):
            target = envelopes[i][1]
            if target > tail[-1]:
                tail.append(target)
                continue
            left = 0
            right = len(tail) - 1
            while left < right:
                mid = (left+right) >> 1
                if tail[mid] < target:
                    left = mid + 1
                else:
                    right = mid
            tail[left] = target
        return len(tail)

Runtime: 164 ms, faster than 60.88% of Python3 online submissions for Russian Doll Envelopes.

Memory Usage: 15 MB, less than 20.00% of Python3 online submissions for Russian Doll Envelopes.

另一种版本:

https://leetcode-cn.com/problems/russian-doll-envelopes/solution/zui-chang-shang-sheng-zi-xu-lie-by-powcai/

class Solution:
    def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
        import bisect
        envelopes.sort(key=lambda x: (x[0], -x[1]))
        arr = []
        for _, y in envelopes:
            loc = bisect.bisect_left(arr, y)
            arr[loc:loc+1] = [y]
        return len(arr)

Runtime: 164 ms, faster than 60.88% of Python3 online submissions for Russian Doll Envelopes.

Memory Usage: 15.1 MB, less than 20.00% of Python3 online submissions for Russian Doll Envelopes.

Last updated

Was this helpful?