重新排列阵列

时间:2014-08-05 18:12:04

标签: arrays algorithm data-structures

给定一个包含整数的数组,修改数组,使得5位于末尾,其余位于开头(保持5之外的元素的相对排序)。

这个问题可以在O(n ^ 2)时间和恒定空间或O(n)时间和O(n)空间中轻松完成。我想知道它是否可以在O(n)时间和O(1)空间中进行。

1 个答案:

答案 0 :(得分:3)

这是我在python中的代码(应该很容易用其他任何语言重写它):

size = len(array)
first_free = 0 #the first position which is still free

for idx in xrange(size): #iterate over all array elements
  if array[idx] != 5: #if it is 5, ignore it.
    array[first_free] = array[idx] #put it to the first free position
    first_free += 1 #increase free position by one

#All elements which are not equal to 5 have been moved to the beginning 
#of the array and their relative order is preserved. There are exactly 
#first_free such elements. So the rest of the elements are equal to 5.
for i in xrange(first_free, size): #fill the tail of the array with 5.
  array[i] = 5 

时间复杂度为O(n),因为此算法仅对数组进行两次迭代 额外的空间复杂性为O(1),因为它仅使用循环计数器,第一个位置索引和大小变量(3个附加变量)。