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%len; 也就是说,当k比数组长度还要大时,就需要对k取余。
public class Solution {
public static void rotate(int[] nums, int k) {
if(nums==null||nums.length==0) return;
if(k<=0) return;
int len=nums.length;
k=k%len;
int[] temp=new int[len*2];
for(int i=0;i<temp.length;i++){
temp[i]=nums[i%len];
}
for(int i=0;i<len;i++){
nums[i]=temp[len-k+i];
}
}
}
本文介绍了一种将数组元素向右旋转k步的算法实现。通过使用临时数组的方式,实现了数组的有效旋转,并提供了完整的Java代码示例。
133

被折叠的 条评论
为什么被折叠?



