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.
思路:一个经典的题目,使用 bisect 库会更好写一些。巧妙之处在于 dp 数组的存储设计。
代码:
from bisect import bisect_left
class Solution:
def lengthOfLIS(self, nums: [int]) -> int:
dp = []
for i in range(len(nums)):
idx = bisect_left(dp, nums[i])
if idx == len(dp):
dp.append(nums[i])
else:
dp[idx] = nums[i]
return len(dp)