p189

LeetCode p189 Rotate Array 题解

1.题目:

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

题意:

输入一个数组,输入一个数字K,将数组末尾的K个数放到数组前面来。
如1234567 输入 3
输出567 1234

2.解题思路:

把数组分两段1234 567
分别反转 4321 765
整体反转 567 1234

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
public class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length; // 整数倍等于无操作
reverse(nums, 0, nums.length - 1 - k);
reverse(nums, nums.length - k, nums.length - 1);
reverse(nums, 0, nums.length - 1);
}

public void reverse(int[] n, int s, int e) {
while (s < e) {
int c = n[s];
n[s] = n[e];
n[e] = c;
s++;
e--;
}

}
}

4.一些总结: