题目
Rotate Array
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.
标签
Array
难度
简单
分析
题目意思是给定一个整形数组,传入一个k参数,另其旋转k次,有点类似队列的感觉,从队头出去K个,然后按照顺序再插入到队尾。仔细观察题目给的例子,可以看出
| ——- | 开始位置 | 现在位置 |
| 数字7 | —–7—– | —–3—– |
| 数字6 | —–6—– | —–2—– |
| 数字5 | —–5—– | —–1—– |
从上面关系,可以看出cur_location = origin_location + k - array_size
因为超出了array_size之后,会重新从队头插入,所以上面的等式变成如下关系
cur_location = (origin_location + k )% array_size
C代码实现
void rotate(int* nums, int numsSize, int k) {
int i=0;
int *array = (int *)malloc(sizeof(int)*numsSize);
for(i=0; i<numsSize; i++)
{
array[(i+k)%numsSize] = nums[i];
}
for(i=0; i<numsSize; i++)
nums[i] = array[i];
free(array);
}
本文探讨了一个常见的数组操作问题:如何将一个整数数组向右旋转k步。文章提供了详细的算法思路,包括通过数学公式确定旋转后的元素位置,并给出了一段C语言的实现代码。
1813

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



