问题描述:
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]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
解题思路:
数组的初始化以及steps题目已经给予,如果把数组看成一个环,我们要做的只是将环进行旋转。steps与数组的length要注意,因为steps可能大于length,这时候需要进行取余。至于数组旋转的过程中会出现值的覆盖问题,需要用到临时的变量(或数组)进行存储,旋转的过程中还要注意方向,否则会超时。
C代码如下:
void rotate(int nums[], int n, int k) {
int temp = k % n;
int val;
if(temp<=(n/2)){
for(int i=0;i<temp;i++){
val = nums[n-1];
for(int j=n-1;j>0;j-- ){
nums[j] = nums[j-1];
}
nums[0] = val;
}
}else{
for(int i=0;i<n-temp;i++){
val = nums[0];
for(int j=0;j<n-1;j++ ){
nums[j] = nums[j+1];
}
nums[n-1] = val;
}
}
}