---
title: "Rotate Array"
author: "KickCode"
date: "2016-02-17T03:46:17Z"
tags: []
categories: ["编程语言"]
slug: "rotate-array"
draft: false
lastmod: "2016-02-17T03:46:17Z"
id: 2276831
url: "https://kickcode.iteye.com/blog/2276831"
---

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可能大于数组的长度。代码如下：

```java

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;
        }
    }
    
}


```