You have two arrays src, tgt, containing two permutations of the numbers 0..n-1. You would like to rearrange src so that it equals tgt. The only allowed operations is “swap a number with 0”, e.g. {1,0,2,3} -> {1,3,2,0} (“swap 3 with 0”). Write a program that prints to stdout the list of required operations.
Practical application:
Imagine you have a parking place with n slots and n-1 cars numbered from 1..n-1. The free slot is represented by 0 in the problem. If you want to rearrange the cars, you can only move one car at a time into the empty slot, which is equivalent to “swap a number with 0”.
Example:
src={1,0,2,3}; tgt={0,2,3,1};
------------------------------------------------------------------------------------------------------------------
You can use an extra O(n) space to get a solution with O(n) time complexity.
1. In a pre-processing step, go through the "source" array, compute the position of each of the 0 to n elements and store in the auxiliary 'position' array.
2. Start at the heads of both source and target array and compare the elements
3. If the elements are the same or the value of the target array ==0 proceed to the next elements. Otherwise go to step 4
4. Find position of 0 using the 'position' array and swap it with the current element 'e' in the source array and update the positions of 0 and 'e' in the position array. Now swap 0 with the target element(found again using the position array)
and after the swap, update their positions in the position array. Advance the pointers of both source and target arrays.
5. Repeat steps 3 & 4 until all the elements are processed.

本文介绍了一种通过仅允许与0交换元素的方法来重新排列数组的问题。此问题类似于停车场中车辆重新排列的问题,其中0代表空闲车位。文章提供了一个解决方案,该方案使用额外的O(n)空间实现O(n)时间复杂度。
1717

被折叠的 条评论
为什么被折叠?



