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];
}
}