[C语言][LeetCode][189]Rotate Array

来源:互联网 发布:yyp2p监控软件使用说明 编辑:程序博客网 时间:2024/06/05 09:04

题目

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);}
0 0
原创粉丝点击