2015年6月7日星期日

[LeetCode] Rotate Array

Problem:

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

Java Code:

public class Solution {
    public void rotate(int[] nums, int k) {
        if (nums == null || nums.length < 2 || k <= 0 || k == nums.length) {
            return;
        }
        if (k > nums.length) {
            k = k % nums.length;
        }
        rotateIJ(nums, 0, nums.length - 1 - k);
        rotateIJ(nums, nums.length - k, nums.length - 1);
        rotateIJ(nums, 0, nums.length - 1);
    }
    
    public void rotateIJ(int[] nums, int i, int j) {
        while (i + 1 <= j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
    }
}

没有评论:

发表评论