简体   繁体   English

使用字典对 O(n) 中的数组进行排序?

[英]Sorting an array in O(n) using dictionary?

Assuming you have an array of numbers that need to be sorted and the following two conditions are true:假设您有一个需要排序的数字数组,并且以下两个条件为真:

  1. A low standard deviation低标准偏差
  2. Memory isn't a constraint Memory 不是约束

How about using dictionary to sort this in O(n), below is the python code:如何使用字典在 O(n) 中排序,下面是 python 代码:

def sortArray(nums: List[int]) -> List[int]:

    # dictionary to store all the numbers in the array as key and number of occurrences as value
    d = {} 
    
    # Keep a track of upper and lower bound of array
    max_num = nums[0]
    min_num = nums[0]
    
    for e in nums:
        if e>max:
            max=e
        if e<min:
            min=e
            
        try:
        #increment the value for "e" if it exists in dictionary
            d[e]=d[e]+1  
        except:
        #add a new key "e"
            d[e]=1 
    
    a=[]
    for i in range(min_num,max_num+1):
        try:
            for j in range(0,d[i]):
                # add the element in new array for d[i] times
                a.append(i)
        except:
            continue
            
    return a

Given the 2 conditions,Are there any scenarios where this code would not work in O(n)?鉴于这 2 个条件,是否存在此代码在 O(n) 中不起作用的情况? Is there something wrong with this approach?这种方法有问题吗?

It is not possible to tell the exact complexity of this procedure because the running time depends on the range of the values, among others.无法说出此过程的确切复杂性,因为运行时间取决于值的范围等。

If this range is fixed, the final double loop adds an element N times.如果这个范围是固定的,最后的双循环会添加一个元素 N 次。 Hence O(N), if the hash table guarantees an O(N) complexity.因此 O(N),如果 hash 表保证 O(N) 复杂度。

But for unbounded N, a fixed range does not make much sense, and it should grow with N. Hence the complexity will be of order O(M(N) + N), where M(N) is the size of the range.但是对于无界的 N,固定范围没有多大意义,它应该随着 N 增长。因此复杂度将是 O(M(N) + N) 的数量级,其中 M(N) 是范围的大小。

It is also worth to note that the append operation does not necessarily feature constant time cost per element.还值得注意的是,append 操作不一定具有每个元素的恒定时间成本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM