Leetcode 300. Longest Increasing Subsequence 动态规划经典题

300. Longest Increasing Subsequence(Medium)

Given an unsorted array of integers, find the length of longest increasing subsequence.
给定一个无序的整数数组,找到其中最长上升子序列的长度。
Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:

There may be more than one LIS combination, it is only necessary for you to return the length.Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?

方法一:
动态规划,dp[] 代表该位的最长上升子序列最大长度。遍历一遍前面比自己小的数比较就行。

    def lengthOfLIS(self, nums):
        if not nums:
            return 0
        dp = [1] * len(nums)
        for i in range(1, len(nums)):
            for j in range(0, i):
                if nums[i] > nums[j]:
                    dp[i] = max(dp[i], dp[j] + 1)
        return max(dp)

方法二:
二分搜索法,维护一个最大增长的子序列List res,遇到小的数就替换,需要注意的是只是替换并没有改变位数,只有后面的数大于最后一位数res才会增加。

    def lengthOfLIS(self, nums):
        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:  #binarysearch 只是替换,并没有增加数
                l, r, mid = 0, len(res) - 1, 0
                while l <= r:
                    mid = (l + r) // 2
                    if res[mid] < nums[i]:
                        l = mid + 1
                    else:
                        r = mid - 1
                res[l] = nums[i]
                print(res)
        return len(res)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 晨曦刚醒 驻足阶前望着渐走渐远的你 你未回头 于是我开始背对着你 假装不是你远去的背影 而是我们背对背相依的柔情 ...
    追忆者阅读 347评论 2 5
  • 《博览币市》是链爱狂为广大币友开设的特色栏目之一,主笔为罗小博。罗小博,拥有8年股票操作经验,6年外汇操作经验,2...
    链爱狂阅读 228评论 0 0
  • 最好的奖励,那一盒浓黑的巧克力,使我的琴声转变。暑假妈妈为我报了一个电子琴的名额,以这来充实我的暑假,这时还有一个...
    峡溪飞瀑阅读 136评论 0 0
  • 我和孩子的父亲离婚两个月了,原因是两个人不会好好说话,我们孩子一周多了,经济每况日下,也是争吵的由头,一说话就吵,...
    afc18a3fe4e5阅读 176评论 0 0
  • 工作量:名单1进店0缔结0 业绩:1970 总结:要跟自己的咨询线保持一致,只有做好向上咨询才能给出伙伴意见,做好...
    甄程很自律阅读 153评论 0 0