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)