当前位置:网站首页>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); // 循环暂停,回到起始位置,角落无人
}
}
};
边栏推荐
- [Unity Getting Started Plan] Basic Concepts (8) - Tile Map TileMap 02
- 请问大家,MySQL全量怎么样可以提高性能呢?我这里瓶颈是在Source上,在不增加并行度的情况下,
- 视频人脸识别和图片人脸识别的关系
- AI+BI+Visualization, Deep Analysis of Sugar BI Architecture
- MATLAB | 一种简易的随机曼陀罗图形生成函数
- How much do you know about the intelligent operation and maintenance service of data warehouse based on DMS?
- Awesome!Coroutines are finally here!Thread is about to be in the past
- 小熊派——无线联网开发
- 生态剧变,电子签名SaaS模式迎来新突破,网络效应加速到来
- 常见分布式理论(CAP、BASE)和一致性协议(Gosssip、Raft)
猜你喜欢
【Unity入门计划】基本概念(6)-精灵渲染器 Sprite Renderer
MPLS的wpn实验
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!.
AI+BI+Visualization, Deep Analysis of Sugar BI Architecture
Yuan xiaolin: Volvo focus on travel security, and put it perfectly
[微信小程序开发者工具] × #initialize
为教育插上数字化的翅膀,网易云信发布「互联网+教育」整体解决方案
TCP 可靠吗?为什么?
小熊派——无线联网开发
一文看懂推荐系统:概要02:推荐系统的链路,从召回粗排,到精排,到重排,最终推荐展示给用户
随机推荐
面了个腾讯35k出来的,他让我见识到什么叫精通MySQL调优
使用VS Code搭建ESP-IDF环境
Research on power flow in DC microgrid based on Newton's method (Matlab code implementation)
"Avnet Embedded Weekly" Issue 276: 2022.07.25--2022.07.31
window.open不显示favicon.icon
不可忽略!户外LED显示屏的特点及优势
MySQL查询语法
CPU个数_核心数_线程数之间的关系
【QT】Qt 给已经开发好的程序快速封装成动态库
一文看懂推荐系统:召回01:基于物品的协同过滤(ItemCF),item-based Collaboration Filter的核心思想与推荐过程
【Unity入门计划】基本概念(8)-瓦片地图 TileMap 02
破解数字化转型困局,企业分析协同场景案例解析
一文看懂推荐系统:召回03:基于用户的协同过滤(UserCF),要计算用户之间的相似度
带你了解什么是 Web3.0
AI+BI+Visualization, Deep Analysis of Sugar BI Architecture
Interpretation of the 2021 Cost of Data Breach Report
TCP 可靠吗?为什么?
建造者模式/生成器模式
How to start an NFT collection
袁小林:沃尔沃专注于出行的安全感,并且把它做到极致