Permute Elements of An Array
Last updated
Last updated
Given an array A
of n
elements and a permutation P
, where P[i]
indicates the location where the current A[i]
goes. Apply P
to A
.
Idea:
Every permutation can be represented by a collection of independent permutations, each of which is cyclic.
In each cycle, alternate elements in A
one by one.
After one location is alternated, deduct len(A)
from the location index. Then after this cycle is done, we know which location is already alternated (locations with negative values).
Time complexity:
Space complexity: