300.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 is4
Solution:
if __name__== "__main__":
def lengthOfLIS(nums):
tails = [0 for _ in range(len(nums))]
size = 0
for x in nums:
i, j = 0, size
while i != j:
m = (i+j)//2
if tails[m]<x:
i = m+1
else:
j = m
tails[i] = x
size = max(i+1, size)
return size
print(lengthOfLIS([10,9,2,5,3,7,101,18]))
tails存放升序尾节点,随着for x in nums: 遍历,tails数组的变化依次为:
[10, 0, 0, 0, 0, 0, 0, 0]
[9, 0, 0, 0, 0, 0, 0, 0]
[2, 0, 0, 0, 0, 0, 0, 0]
[2, 5, 0, 0, 0, 0, 0, 0]
[2, 3, 0, 0, 0, 0, 0, 0]
[2, 3, 7, 0, 0, 0, 0, 0]
[2, 3, 7, 101, 0, 0, 0, 0]
[2, 3, 7, 18, 0, 0, 0, 0]
size保存当前最大的递增子序列长度。