zoukankan      html  css  js  c++  java
  • 最长递增子串的长度

    给出一个无序的整形数组,找出它的最大升序子序列。
    示例数组 arr[] = {10, 9, 2, 5, 3, 7, 101, 18},
    数组arr的最长升序子序列是 {2, 3, 7, 101},因此长度是4。
    解题思路:
    定义数组tmp记录当前最大升序子串(∴tmp必然升序),用tmp的末位元素对比目标序列nums[i]开始的每个元素,若当前nums元素 > tmp末位元素,当前nums元素插入tmp,否则,我们用二分查找法在tmp数组找第一个不小于num[i]的数下标,否则用当前nums元素替换tmp中下标元素即可。
    代码如下:
    def binary_search(nums,key):
        if len(nums)<1:
            return -1
        high=len(nums)-1
        low=0
        while low<=high:
            mid=(low+high)//2
            if low<=high and nums[mid]>key:
                high=mid-1
            elif low<=high and nums[mid]<key:
                low=mid+1
            else:
                return mid
        return low
    
    nums=[i for i in input().strip().split(" ")]
    target=[]
    target.append(nums[0])
    for i in range(1,len(nums)):
        if nums[i]>=target[-1]:
            target.append(nums[i])
        else:
            position=binary_search(target, nums[i])
            target[position]=nums[i]
    print(target)
    print(len(target))
  • 相关阅读:
    Matplotlib.pyplot 三维绘图
    Matplotlib.pyplot 二维绘图
    面对对象进阶
    面对对象基础
    python安装第三方模块
    json & pickle
    os模块
    sys模块
    正则表达式
    Python2与Python3的编码差异
  • 原文地址:https://www.cnblogs.com/tsdblogs/p/9875755.html
Copyright © 2011-2022 走看看