简体   繁体   中英

Rearranging the array

Given an array containing integers, modify the array such that the 5's are at the end and the rest are at the beginning (maintaining the relative ordering of the elements other than 5).

This problem can be easily done in O(n^2) time and constant space or O(n) time and O(n) space. I was wondering if its possible to do it in O(n) time and O(1) space.

Here is my code in python(it should be easy to rewrite it in any other language):

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 

Time complexity is O(n) because this algorithm iterates over the array only twice.
Additional space comlexity is O(1) because it uses only a loop counter, first position index and size variables(3 additional variables).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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