LeetCode初级算法(数组篇)-----旋转数组
参考:https://blog.csdn.net/qq_28584889/article/details/83655019
题目
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
结题思路
移动交换

代码
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
int temp1,temp2,index,count=0;
k = k%len;
if(k==0)
return;
for(int i =0;i<=k;i++){
if(count>=len){
break;
}
index = i;
temp1 = nums[i];
while((index+k)%len!=i){ //判断条件
temp2 = nums[(index+k)%len];
nums[(index+k)%len] = temp1; //进行交换
index = (index+k)%len; //更新索引下标,步进为k
temp1 = temp2; //更新暂存变值
count++;
}
nums[i] = temp1; //形成闭环
count++;
}
}
};
``
版权声明:本文为qq_36302310原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。