2015年9月17日星期四

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.
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Show Tags
Show Similar Problems








public class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        int left = nums.length - k;
        int right = k;
     
        int[] leftNums = new int[left];
        for (int i = 0; i < left; i++) {
            leftNums[i] = nums[i];
        }
        int[] rightNums = new int[right];
        for (int i = 0; i < right; i++) {
            rightNums[i] = nums[i + left];
        }
        for (int i = 0; i < right; i++) {
            nums[i] = rightNums[i];
        }
        for (int i = 0; i < left; i++) {
            nums[i + right] = leftNums[i];
        }
    }
}

===========

public class Solution {
    public void rotate(int[] nums, int k) {
        k = k % nums.length;
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }
   
    private void reverse(int[] nums, int s, int e) {
        while (s < e) {
            int tmp = nums[s];
            nums[s] = nums[e];
            nums[e] = tmp;
            s++;
            e--;
        }
    }
}

没有评论:

发表评论