美文网首页
8.21 - hard - 73

8.21 - hard - 73

作者: 健时总向乱中忙 | 来源:发表于2017-08-22 00:07 被阅读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
            
    

    相关文章

      网友评论

          本文标题:8.21 - hard - 73

          本文链接:https://www.haomeiwen.com/subject/nwqkdxtx.html