给定一个无序的整数数组,找到其中最长上升子序列的长度。
示例:
输入:[10,9,2,5,3,7,101,18]
输出: 4 解释: 最长的上升子序列是[2,3,7,101],
它的长度是4
。
说明:
- 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
- 你算法的时间复杂度应该为 O(n2) 。
进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?
DP写法:
class Solution:
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
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
还是DP两步走:
- dp[i]表示到i为止的最长上升子序列
- dp方程:dp[i] = max(dp[i],dp[j]+1) i∈[0,n-1] j∈[0,i-1]
注:判断条件是nums[i] > nums[j]
二分查找法:
class Solution:
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
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 = 0,len(res)-1
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)