8.21 - hard - 73

2017-08-22  本文已影响0人  健时总向乱中忙

354. Russian Doll Envelopes

简单的DP的话,会TLE,worst case O(n^2)

利用LIS这种题目的二分法的解法,真是万万没想到。基本想法就是把每一个新进来的元素都插入到dp中,最后计算总长度。

class Solution(object):
    def maxEnvelopes(self, envelopes):
        """
        :type envelopes: List[List[int]]
        :rtype: int
        """
        if len(envelopes) <= 1:
            return len(envelopes)
        
        envs = sorted(envelopes, key=lambda x: (x[0], -x[1]))
        dp =  [0]*len(envs)
        l = 0
        for e in envs:
            index = self.search(dp, 0, l, e[1])
            dp[index] = e[1]
            if index == l:
                l += 1
        return l
    
    def search(self, dp, start, end, target):
        # find the most left index to insert target
        while start + 1 < end:
            mid = (start + end) / 2
            if dp[mid] < target:
                start = mid
            else:
                end = mid
        
        if dp[start] >= target:
            return start
        else:
            return end
        
上一篇下一篇

猜你喜欢

热点阅读