leetcode [#189]

目录

题目

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

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

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
int[] result = new int[len];
for(int p = 0; p < len; p++){
result[p] = nums[(len - (k % len) + p) % len];
}
for(int q = 0; q < len; q++) {
nums[q] = result[q];
}
}
}

注意事项

  1. 找到下标规律,取相应元素即可。
  2. 该方法效率一般,更好的方法如下:
    1
    2