• 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)

      

  • 相关阅读:
    uniq 只能相邻行去重
    uniq 只能相邻行去重
    uniq 只能相邻行去重
    KVO(1)
    KVO(1)
    KVO(1)
    KVO(1)
    解决 Retrofit 多 BaseUrl 及运行时动态改变 BaseUrl ?
    jquery 请求成功后
    事故现场:MySQL 中一个双引号的错位引发的血案
  • 原文地址:https://www.cnblogs.com/xiao-xue-di/p/10286385.html
Copyright © 2020-2023  润新知