Sunday, March 8, 2015

Rotate Array

Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Solution
假设nums[] = 1 2 3 4 5, k = 3, 如图:
从index=0(第一个数)开始移动,第一个数移动到(postion + k) % len位上, 将(postion + k) % len位上的数先存到temp里, 按此规律往下移动。

Run time complexity is O(n), constant space.
public class Solution {
    public void rotate(int[] nums, int k) {
        if(nums == null || nums.length == 0)
            return;
        
        int len = nums.length;
        int count = 0;
        int j = 0;
        while(count < len) {
            int postion = j;
            int val = nums[postion];
            do {
                postion = (postion + k) % len;
                int temp = nums[postion];
                nums[postion] = val;
                val = temp;
                count++;
            }while(postion != j);  //position = j 意味着开始重复这个跳跃的循环
            j++;  //跳出当前循环,重新开始下一个循环
        }
    }
}

No comments:

Post a Comment