【LeetCode】最长上升子序列 python ★★★★★★

最详解析:https://blog.csdn.net/qq_17550379/article/details/82871892

给定一个无序的整数数组,找到其中最长上升子序列的长度。

示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4 
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

方法一:动态规划

记录每个元素前面出现的比它小的元素个数。

lst = [10,9,2,5,3,7,101,18]
l = len(lst)
if l <= 1:
    print(l)
else:
    data = [1]*l
    for i in range(1, l):
        for j in range(i):
            if lst[i] > lst[j]:
                data[i] = max(data[i], data[j] + 1)
    print(max(data))

 方法二:二分查找

详细思路:https://blog.csdn.net/u012479682/article/details/79652361

class Solution(object):
    def lengthOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = len(nums)
        if l == 0:
            return 0
        tmp = [nums[0]]
        j = 0
        for i in range(1,l):
            if nums[i] <= tmp[0] and j == 0:
                tmp[0] = nums[i]
            elif nums[i] > tmp[-1]:
                tmp.append(nums[i])
                j = 1
            elif tmp[0] < nums[i] and nums[i] < tmp[-1]:
                loc = self.twoFind(tmp,nums[i],0,len(tmp)-1)
                tmp[loc] = nums[i]
                j = 1
        return(len(tmp))
    
############# 二分查找 ###################
    def twoFind(self,nums,t,first,last):
        if first > last:
            return -1
        mid = (first+last)//2
        if t <= nums[mid]:  ## 和普通二分查找不太一样的地方,找到nums[k-1] < t = nums[mid-1]:
                return mid
            else:
                last = mid - 1
        else:
            first = mid + 1
        return self.twoFind(nums,t,first,last)
            

 

你可能感兴趣的:(剑指offer_Java)