给定一个长度为 n 的数组 arr,求它的最长严格上升子序列的长度。
所谓子序列,指一个数组删掉一些数(也可以不删)之后,形成的新数组。例如 [1,5,3,7,3] 数组,其子序列有:[1,3,3]、[7] 等。但 [1,6]、[1,3,5] 则不是它的子序列。
我们定义一个序列是 严格上升 的,当且仅当该序列不存在两个下标 和 满足 且 。
数据范围:
要求:时间复杂度 , 空间复杂度
[6,3,1,5,2,3,7]
4
该数组最长上升子序列为 [1,2,3,7] ,长度为4
class Solution: def LIS(self , arr: List[int]) -> int: #设置数组长度大小的动态规划辅助数组 dp = [1 for i in range(len(arr))] res = 0 for i in range(1, len(arr)): for j in range(i): #可能j不是所需要的最大的,因此需要dp[i] < dp[j] + 1 #遍历数组中所有的数,再遍历当前数之前的所有数,只要前面某个数小于当前数, #则要么长度在之前基础上加1,要么保持不变,取两者中的较大者 if arr[i] > arr[j] and dp[i] < dp[j] + 1: #i点比j点大,理论上dp要加1 dp[i] = dp[j] + 1 #找到最大长度 res = max(res, dp[i]) return res
class Solution: def LIS(self , arr: List[int]) -> int: # write code here cnt = [-int(1e9+7)] for n in arr: if n>cnt[-1]: cnt.append(n) else: left = 0 right = len(cnt)-1 while left<right: mid = (left+right+1)//2 if cnt[mid]>=n: right = mid-1 else: left = mid cnt[left+1] = n return len(cnt)-1