题目描述:
给你一个整数数组 nums
,找到其中最长严格递增子序列的长度。
子序列 是由数组派生而来的序列,删除(或不删除)数组中的元素而不改变其余元素的顺序。例如,[3,6,2,7]
是数组 [0,3,1,6,2,2,7]
的
子序列
。
示例 1:
输入:nums = [10,9,2,5,3,7,101,18] 输出:4 解释:最长递增子序列是 [2,3,7,101],因此长度为 4 。
示例 2:
输入:nums = [0,1,0,3,2,3] 输出:4
示例 3:
输入:nums = [7,7,7,7,7,7,7] 输出:1
提示:
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
我的作答:
两层for循环,遍历,如果大就添加;
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
dp = [1]*len(nums) #因为最短的子序列就是包括自身,所以初始化为1
res = 0
for i in range(len(nums)):
for j in range(i):
if nums[i]>nums[j]: #如果i比j大,就比较后添加
dp[i] = max(dp[i], dp[j]+1)
if dp[i]>res: #更新res
res = dp[i]
return res
参考:
太炫技了,我的评价是算了(?)定义 g[i] 表示长为 i+1 的上升子序列的末尾元素的最小值。
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ng = 0 # g 的长度
for x in nums:
j = bisect_left(nums, x, 0, ng)
nums[j] = x
if j == ng: # >=x 的 g[j] 不存在
ng += 1
return ng