查看: 2009| 回复: 3
跳转到指定楼层
上一主题 下一主题
收起左侧

[动态规划] Longest non-decreasing subsequence

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
Leetcode上有经典题longest increasing subsequence,最优算法是O(n log n)。
但是如果把题稍微改改变成non-decreasing,好像那个最优解就不能直接用了。但是至少还有O(n^2)的DP解。

问题:Given an unsorted array of integers, find the length of longest non-decreasing subsequence.

上一篇:分享两道有趣的国内OA题目
下一篇:facebook设计distributed system常见问题
🔗
yxchen_ethan 2019-11-11 08:42:56 | 只看该作者
全局:
還是可以做O(n log n), 方法也差不多.
回复

使用道具 举报

🔗
 楼主| TreeSet 2019-11-11 09:02:52 | 只看该作者
全局:
yxchen_ethan 发表于 2019-11-10 19:42
還是可以做O(n log n), 方法也差不多.

那么怎么做呢?
回复

使用道具 举报

🔗
yxchen_ethan 2019-11-11 09:04:36 | 只看该作者
全局:
原本問題 Longest increasing subsequence:
# python

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        LIS = [nums[0]]
        
        for num in nums[1:]:
            i = bisect_left(LIS, num)
            if i == len(LIS):
                LIS.append(num)
            elif num < LIS[i]:
                LIS[i] = num
        
        print(LIS)
        return len(LIS)

若是題目改成non-decreasing, 把bisect_left 改成 bisect, 就是non-decreasing的解答了.

bisect和bisect_left, 只差在binary search的時候, comparison是 greater 還是 greater or equal, 回傳的是[lo, up)的上界還是下界(如下).
複雜度同樣是O(log n). 所以longest non-decreasing 一樣O(n log n)可以解掉.

def _bisect(a, x):
    lower_bound, upper_bound = 0, len(a)
    while lower_bound < upper_bound:
        mid = (lower_bound + upper_bound) // 2
        if a[mid] > x:
          upper_bound = mid
        else:
          lower_bound = mid + 1
    return upper_bound

def _bisect_left(a, x):
    lower_bound, upper_bound = 0, len(a)
    while lower_bound < upper_bound:
        mid = (lower_bound + upper_bound) // 2
        if a[mid] >= x:
          upper_bound = mid
        else:
          lower_bound = mid + 1
    return lower_bound

评分

参与人数 1大米 +2 收起 理由
eenjoyzoo + 2 很有用的信息!

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表