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步旋转一个有n个元素的数组
算法分析
方法一
需要一个额外的数组:通过给定的k和当前索引i,求得变换后对应的索引值。
Java代码
public class Solution {
public void rotate(int[] nums, int k) {
int[] extraNum = new int[nums.length];
for (int i = 0; i < nums.length; i ++) {
extraNum[(i + k) % nums.length] = nums[i];//索引转换
}
for (int i = 0; i < nums.length; i ++)
nums[i] = extraNum[i];
}
}