【DP】300. Longest Increasing Subsequence

时间复杂度为o(n**2)时:

class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        
        table=[]       
        for i in range(len(nums)):
            table.append(1);
            
        for i in range(len(nums)):
            for j in range(i):
                if nums[j]<nums[i]:
                    table[i]=max(table[i],1+table[j])
        return max(table)

时间复杂度为o(nlogn)时:

class Solution:
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        
        if len(nums)==0:
            return 0
        table = []
        for i in range(len(nums)):
            low = 0
            high = len(table)-1
            while low<=high:
                mid = (low+high)//2
                if table[mid]<nums[i]:
                    low = mid + 1
                else:
                    high = mid - 1
                
            if low >= len(table):
                table.append(nums[i])
            else:
                table[low]=nums[i]
        
        return len(table)
                        
                    
                        

猜你喜欢

转载自blog.csdn.net/leetcodecl/article/details/81148872