Algorithm to apply permutation in constant memory space

后端 未结 8 1575
温柔的废话
温柔的废话 2020-12-13 21:29

I saw this question is a programming interview book, here I\'m simplifying the question.

Assume you have an array A of length n, and you ha

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 22:00

    The simplest case is when there is only a single swap for an element to the destination index. for ex: array=abcd perm =1032. you just need two direct swaps: ab swap, cd swap

    for other cases, we need to keep swapping until an element reaches its final destination. for ex: abcd, 3021 starting with first element, we swap a and d. we check if a's destination is 0 at perm[perm[0]]. its not, so we swap a with elem at array[perm[perm[0]]] which is b. again we check if a's has reached its destination at perm[perm[perm[0]]] and yes it is. so we stop.

    we repeat this for each array index. Every item is moved in-place only once, so it's O(N) with O(1) storage.

    def permute(array, perm):
    
    for i in range(len(array)):
        elem, p = array[i], perm[i]
    
        while( p != i ): 
            elem, array[p] = array[p], elem  
            elem = array[p]
            p = perm[p]
    
    return array
    

提交回复
热议问题