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.

思路: space O(1)解法,time O(n), 经典的三步翻转法. 先找到offset k % n

public class Solution {
    public void rotate(int[] nums, int k) {
        if (nums.length == 0 || nums == null) return;
        int n = nums.length;
        k %= n; // offset
        reverseString(nums, 0, n - 1);
        reverseString(nums, 0,k - 1);
        reverseString(nums, k,n - 1);
    }

    public void reverseString(int [] nums, int low, int high) {
        while (low < high) {
            int tmp = nums[high];
            nums[high] = nums[low];
            nums[low] = tmp;
            low++;
            high--;
        }
    }
}

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