Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 如何在O(n)时间和O(1)空间中对长度为n的0和1数组进行排序?我们能把它推广到0,1,2,…,的数组吗。。。?_Sorting - Fatal编程技术网

Sorting 如何在O(n)时间和O(1)空间中对长度为n的0和1数组进行排序?我们能把它推广到0,1,2,…,的数组吗。。。?

Sorting 如何在O(n)时间和O(1)空间中对长度为n的0和1数组进行排序?我们能把它推广到0,1,2,…,的数组吗。。。?,sorting,Sorting,我想对0和1的数组进行排序。我必须在线性时间和恒定空间中对它进行排序。如果不显式地计算0和1的数量,我如何才能做到这一点 我是这样做的: sort(array): Q0 = Queue() Q1 = Queue() for i in (0, n-1): if array[i] == 0: Q0.push(array[i]) if array[i] == 1: Q1.push(array[i]

我想对0和1的数组进行排序。我必须在线性时间和恒定空间中对它进行排序。如果不显式地计算0和1的数量,我如何才能做到这一点

我是这样做的:

sort(array):
    Q0 = Queue()
    Q1 = Queue()
    for i in (0, n-1):
        if array[i] == 0:
            Q0.push(array[i]) 
        if array[i] == 1:
            Q1.push(array[i])
    j = 0
    while Q0:
        array[j] = Q0.pop()
        j += 1
    while Q1:
        array[j] = Q1.pop()
        j += 1
我认为我的解决方案是正确的,并且已经按时完成,但我不确定O1空间。有什么帮助吗


此外,我们可以将排序推广到0、1、2数组吗?

这个想法是通过保留两个指针,将所有的1交换到数组的末尾,将0交换到数组的开头。我指向第一个索引,它有一个1

下面是一个伪代码:

i = 1
for (j = 1 to n)
    if(a[j] == 0)
        swap(a[i], a[j])
        i++

以下是经过测试/正在使用的Python:

# sort array of length n containing values of only 0 or 1
# in time O(n) and space O(1)

a = [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
        0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
first = 0
last  = len(a)-1
print a

# note: don't need temp since values are only 0 and 1
while(last>first):
    if a[first] == 1:
        a[first] = a[last]
        a[last]  = 1
        last    -= 1
    else:
        first   += 1

print a

您的队列占用空间,而不是O1。谢谢。是的,这就是问题所在。那么您有什么解决方案吗?为什么不能显式地计算0和1的数量?通过对数组进行一次遍历来计算0和1的数量,然后根据计数器生成输出。我很确定这是重复的。我无法计算0和1的数量,因为问题是这样的。我的意思是练习的陈述是这样的。你测试了吗?第一次通过i和j=1,因此如果a[1]==0 swapa[1],a[1]将a[1]与自身交换没有任何错误。如果a[1]!=0在循环开始时,我永远不会前进,循环也不会做任何事情。user2357112:你是对的。if语句应该是[j]==0,而不是[i]==0。现在修好了。