Given an unsorted array of integers, find the length of longest increasing subsequence.
Example
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that 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?
classSolution(object):deflengthOfLIS(self,nums):""" :type nums: List[int] :rtype: int """# n^2: # dp[i]: the longest increasing subsequencedp=[1]*len(nums)foriinrange(len(nums)):forjinrange(i):ifnums[i]>nums[j]anddp[i]<dp[j]+1:dp[i]=dp[j]+1rt=0foriinrange(len(nums)):ifrt<dp[i]:rt=dp[i]returnrt# n(logn)# dp: is an array to record the longest increasing subsequencedp=[]foriinrange(len(nums)):start=0end=len(dp)-1# binary search dp, find the place dp[mid] < nums[i]whilestart<=end:mid=(start+end)/2ifdp[mid]>=nums[i]:end=mid-1else:start=mid+1ifstart>=len(dp):dp.append(nums[i])else:dp[start]=nums[i]returnlen(dp)