300. 最长上升子序列

 

300. 最长上升子序列

方法一

class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        nums = [10, 9, 2, 5, 3 ,7, 101, 18]
        """
        
        if not nums: return 0
        dp = [1] * len(nums)
        res = 1
        for i in range(len(nums)):
            for j in range(i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[i], dp[j] + 1)
            res = max(res, dp[i])
        return res

 

方法二

class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        nums = [10, 9, 2, 5, 3 ,7, 101, 18]
        """
        if not nums:
            return 0
        lis = [nums[0]]
        for i in range(1, len(nums)):
            if nums[i] > lis[-1]:
                lis.append(nums[i])
            else:
                for j in range(len(lis)):
                    if lis[j] >= nums[i]:
                        lis[j] = nums[i]
                        break
        return len(lis)

 

方法三

class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        nums = [10, 9, 2, 5, 3 ,7, 101, 18]
        """
        
        
        if not nums: return 0
        res = [nums[0]]
        for i in range(1, len(nums)):
            if nums[i] > res[-1]:
                res.append(nums[i])
            else:
                l, r, mid = 0, len(res)-1, 0
                while l <= r:
                    mid = (l + r) // 2
                    if nums[i] > res[mid]:
                        l = mid + 1
                    else:
                        r = mid - 1
                res[l] = nums[i]
        return len(res)

 

  

posted @ 2019-01-18 10:37  小学弟-  阅读(164)  评论(0编辑  收藏  举报