NC91 最长上升子序列(三)

描述

给定数组 arr ,设长度为 n ,输出 arr 的最长上升子序列。(如果有多个答案,请输出其中 按数值(注:区别于按单个字符的ASCII码值)进行比较的 字典序最小的那个)

数据范围:10000000000≤n≤200000,0≤arri​≤1000000000

要求:空间复杂度 O(n),时间复杂度 O(nlogn)

示例1

输入:

[2,1,5,3,6,4,8,9,7]

返回值:

[1,3,4,8,9]

示例2

输入:

[1,2,8,6,4]

返回值:

[1,2,4]

说明:

其最长递增子序列有3个,(1,2,8)、(1,2,6)、(1,2,4)其中第三个 按数值进行比较的字典序 最小,故答案为(1,2,4)

解题思路:

贪心 + 二分查找

题解 | #最长递增子序列#_牛客博客

Python代码:

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# retrun the longest increasing subsequence
# @param arr int整型一维数组 the array
# @return int整型一维数组
#
class Solution:
    def search(self, nums, target):
        i, j = -1, len(nums)
        while i + 1 < j:
            mid = i + (j - i) // 2
            if nums[mid] < target:
                i = mid
            else:
                j = mid
        return j
    def LIS(self , arr: List[int]) -> List[int]:
        # write code here
        res = []
        max_length = []
        n = len(arr)
        for num in arr:
            if not res or num > res[-1]:
                res.append(num)
                max_length.append(len(res))
            else:
                loc = self.search(res, num)
                res[loc] = num
                max_length.append(loc + 1)
        maxlen = len(res) 
        for i in range(n - 1, -1, -1):
            if maxlen == max_length[i]:
                res[maxlen - 1] = arr[i]
                maxlen -= 1
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值