JunyiCode
4/22/2020 - 3:32 PM

189. Rotate Array

k %= len;

/*
Note:
面试时考虑全面
  特殊情况nums.length << k
    k %= len;
*/


class Solution {
    public void rotate(int[] nums, int k) {
        if(nums == null || nums.length == 0)
            return;
        int len = nums.length;
        k %= len;
        
        reverse(nums, 0, len - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, len - 1);
    }
    
    
    private void reverse(int[] nums, int start, int end) {
        while(start < end) {
            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
            start++;
            end--;
        }
    }
}