题目描述:
给你一个数组,将数组中的元素向右轮转 k
个位置,其中 k
是非负数。
示例:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
思路:
使用额外的数组
用额外的数组将元素放到正确的位置,用n表示数组长度,先遍历原数组,将原数组下标为i的元素放至新数组下标为(i+k)mod n的位置{mod n是为了防止k过大},最后将新数组拷贝到原数组即可
代码:
public void rotate(int[] nums,int k){
int n=nums.length;
int[] newArr=new int[n];
for(int i=0;i<n;i++){
newArr[(i+k)%n]=nums[i];
}
System.arraycopy(newArr,0,nums,0,n);
}