当前位置:网站首页>leetcode:189. 轮转数组
leetcode:189. 轮转数组
2022-08-03 16:05:00 【OceanStar的学习笔记】
题目来源
题目描述
题目解析
使用临时数组
可以用一个临时数组,先把原数组的值存放到一个临时数组中,然后再把临时数组的值重新赋给原数组,重新赋值的时候要保证每个元素都要后移k位,如果超过数组长度就重头开始
class Solution {
public:
// 1 <= nums.length <= 10^5
void rotate(vector<int>& nums, int k) {
int N = nums.size();
k = k % N;
if(k == 0){
return;
}
std::vector<int> temp(N);
//把原数组值放到一个临时数组中,
for (int i = 0; i < N; i++) {
temp[i] = nums[i];
}
//然后在把临时数组的值重新放到原数组,并且往右移动k位
for (int i = 0; i < N; i++) {
nums[(i + k) % N] = temp[i];
}
}
};
多次反转
class Solution {
public:
// 1 <= nums.length <= 10^5
void rotate(vector<int>& nums, int k) {
int N = nums.size();
k = k % N;
if(k == 0){
return;
}
std::reverse(nums.begin(), nums.end());
std::reverse(nums.begin(), nums.begin() + k);
std::reverse(nums.begin() + k, nums.end());
}
};
连环怼
class Solution {
public:
// 每次把一个元素弄到对应位置去
// 1 <= nums.length <= 10^5
void rotate(vector<int>& nums, int k) {
int N = nums.size();
k = k % N;
int count = 0; // 记录交换位置的次数,n个同学一共需要换n次
for (int start = 0; count < N; ++start) {
int curr = start; // 从0位置开始换位子
int prev = nums[curr];
do{
//下一个坐标
int next = (curr + k) % N;
//交换
int tmp = nums[next];
nums[next] = prev;
prev = tmp;
//更新当前位置
curr = next;
count++;
}while (start != curr); // 循环暂停,回到起始位置,角落无人
}
}
};
边栏推荐
猜你喜欢
随机推荐
【翻译】关于扩容一个百万级别用户系统的六个课程
Common distributed theories (CAP, BASE) and consensus protocols (Gosssip, Raft)
Not to be ignored!Features and advantages of outdoor LED display
视频人脸识别和图片人脸识别的关系
DataGrip数据仓库工具
一文看懂推荐系统:召回02:Swing 模型,和itemCF很相似,区别在于计算相似度的方法不一样
元宇宙系列--Value creation in the metaverse
Kubernetes 笔记 / 入门 / 生产环境 / 容器运行时
#夏日挑战赛# HarmonyOS 实现一个绘画板
使用 PowerShell 将 Windows 转发事件导入 SQL Server
可复现、开放科研、跨学科合作:数据驱动下的科研趋势及应用方案
How to get the 2 d space prior to ViT?UMA & Hong Kong institute of technology & ali SP - ViT, study for visual Transformer 2 d space prior knowledge!.
MPLS的wpn实验
MySQL窗口函数 OVER()函数介绍
MATLAB | 七夕节快到了,还不给朋友安排上这个咕呱小青蛙?
出海季,互联网出海锦囊之本地化
13 and OOM simulation
下午见!2022京东云数据库新品发布会
Small Tools (4) integrated Seata1.5.2 distributed transactions
uniapp的webview滑动缩放