Leetcode brushing record-300. The longest ascending subsequence (to be added: the method with time complexity O (nlogn))

Insert picture description here
To be added: The method with
time complexity O (nlogn)
——————————————————————————————————————————————————
We first consider the time complexity O (n ^ 2) the method
according to the characteristics of the subject, the presence of substantial overlap problem
Let us think that the use of dynamic programming
is defined as a sub-problem:
find the current location of the end of the longest sequence length increased
as described for [10,9,2,5,3,7,101 , 18]
The length of the longest ascending subsequence with each position as the end is
[1,1,1,2,2,3,1,4]
Then the relationship between dp [i] and the former is:
we call nums [ 0: i-1] This subsequence contains all the numbers smaller than nums [i], the sequence is S
dp [i] = max (dp [j]) + 1, j∈S.
Finally, we return max ( dp)

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        if nums == []:
            return 0
        dplist = []
        length = len(nums)
        for i in range(length):
            if i == 0:
                dplist.append((1))
                #dplist中存放一个个数字,
                #dplist[i]是以i位置为结尾的最长上升子序列的长度,
            else:
                tempmax = -1
                tempindex = -1
                for j in range(i):
                    if nums[j] < nums[i]:
                        if dplist[j] > tempmax:
                            tempmax = dplist[j] 
                            tempindex = j
                if tempindex == -1:#nums[0:i-1]中没有比nums[i]更小的
                    dplist.append(1)
                else:
                    dplist.append(dplist[tempindex] + 1)
        return max(dplist)


Published 43 original articles · praised 14 · 20,000+ views

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105102148