DP、二分-LeetCode300. 最长上升子序列(Python)

Hedva ·
更新时间:2024-09-20
· 927 次阅读

1、题目描述

给定一个无序的整数数组,找到其中最长上升子序列的长度。

输入: [10,9,2,5,3,7,101,18] 输出: 4  解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。 说明:可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。 2、代码详解 法一:DP,O(N^2)

class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 dp = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: dp[i] = max(dp[i], dp[j] + 1) return max(dp) nums = [10, 9, 2, 5, 3, 7, 101, 18] s = Solution() print(s.lengthOfLIS(nums)) 法二:二分查找,O(NlogN) class Solution(object): def lengthOfLIS(self, nums): """ :type nums: List[int] :rtype: int """ tails = [0] * len(nums) size = 0 for x in nums: i, j = 0, size while i != j: m = (i + j) / 2 if tails[m] < x: i = m + 1 else: j = m tails[i] = x size = max(i + 1, size) return size
作者:NLP_victor



leetcode dp 二分 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号