ITeye博客

Rotate Array

KickCode · 2016-02-17 03:46 · Leetcode · 编程语言 · Markdown

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array is rotated to .

将一个数组右移k步,如果我们直接移动k次,会超时。我们可以先反转后k个元素,然后在反转前length - k个元素,最后将整个数组反转,就得到了结果。k在运算的时候要先于数组取模,因为k可能大于数组的长度。代码如下:


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


评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。