gpt4 book ai didi

algorithm - 如何在 O(n) 中对具有给定范围的列表进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:52:17 26 4
gpt4 key购买 nike

如果我有一个大小为 n 的列表,并且我知道列表中的数字将在 1 到 2n 之间,我将如何在最坏情况为 O(n) 的情况下解决它?

我在想,如果它在 1 和 n 之间,我可以只取数字并将它与数组中该数字的值 - 1 交换,但如果有任何重复,它就不会排序。

我正在考虑对数字在 1 到 2n 之间的列表采用类似的方法,但我似乎无法弄清楚。有什么帮助吗?

最佳答案

Counting Sort 在您的情况下可以在 O(n) 中运行。看看维基百科的定义

counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items

http://en.wikipedia.org/wiki/Counting_sort

关于algorithm - 如何在 O(n) 中对具有给定范围的列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20308822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com