【问题标题】:Why does this solution have O(nlogn) complexity?为什么这个解决方案有 O(nlogn) 复杂度?
【发布时间】:2019-04-06 19:17:31
【问题描述】:

给定一个整数数组,返回一个新数组,其中每个元素 新数组是它右边的较小元素的数量 原始输入数组中的元素。 例如,给定数组 [3, 4, 9, 6, 1],返回 [1, 1, 2, 1, 0]。

import bisect

nums = list(input().split())
nums_to_the_right = []
result = []
sorted_nums = []

for num in reversed(nums):
    index = bisect.bisect_left(sorted_nums, num)
    result.append(index)
    bisect.insort(sorted_nums, num)

result.reverse()
print(result)

此代码打印正确的结果。 bisect_left 函数应返回索引,当前元素必须具有该索引才能使数组排序。 insort 函数将元素放入数组中,使数组保持排序状态。我希望整段代码具有 O(n^2) 复杂性,但据说需要 O(nlogn) 才能工作。请告诉我,为什么?

【问题讨论】:

    标签: python bisect


    【解决方案1】:

    bisect 模块使用binary search algorithm 查找插入索引。此算法每次插入的复杂性 - O(logn)(您可以通过链接阅读非常详细的说明)。你有 n 个元素,所以最终的复杂度是 O(nlogn)。最终的result.reverse() 复杂度为O(n),因此在汇总复杂度计算中可以省略。

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多