189. 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.

[show hint]

Related problem: Reverse Words in a String II

public class Solution {
    public void rotate(int[] nums, int k) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return;
        }
        // Error control.
        if (k == 0) {
            return;
        }
        k = k % nums.length;
        int len = nums.length;
        // Pay attention to the index.
        reverse(0, len - 1, nums);
        // After the first revers, last k items have already been moved to the front.
        reverse(0, k - 1, nums);
        reverse(k, len - 1, nums);
    }

    private void reverse(int left, int right, int[] nums) {
        int temp;
        // It's better to use offset, clearer.
        for (int i = 0; i <= (right - left - 1) / 2; i++) {
            temp = nums[left + i];
            nums[left + i] = nums[right - i];
            nums[right - i] = temp;
        }
        /**
        while (left < right) {
            int temp = nums[left];
            nums[left] = nums[right];
            nums[right] = temp;
            left++; right--;
        }
         */
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s