当前位置:网站首页>leetcode每日一练:旋转数组
leetcode每日一练:旋转数组
2022-07-05 17:17:00 【利刃Cc】

链接: 旋转数组
要求我们转一次,就是把最后面的数移到最前面来,然后其他数字保持顺序往后移动一步。
常规思路: 就是用while循环,题目要求我们轮转n次,我们就将后n个数字分别移到最前面去。这种思路虽然行得通,但是仔细想,每次将前面的数字向后移,这个时间复杂度是不低的,所以我们这里不讲这种常规思路。
新思路: 题目要我们轮转数组,其实我们可以先将整个数组翻转顺序,然后再将前n - 1个数翻转顺序,最后将后numsSize - n个数翻转顺序(假设这里数组个数为numsSize个),其实就完成了数组轮转。
注:这里有一个关键的点,就是如果翻转n次,而n等于数组的长度numsSize的话,其实就是原数组不动,以此类推,所以我们可以对n进行一下处理。
而且这种思路的空间复杂度是O(1)的!
代码:
void partRotate(int* a, int left, int right)
{
//使用左右指针的方法
while(left < right)
{
int tmp = a[left];
a[left] = a[right];
a[right] = tmp;
left++;
right--;
}
}
void rotate(int* nums, int numsSize, int k){
k %= numsSize;
//若k模完长度为0,则无需轮转
if(k == 0)
return;
partRotate(nums, 0, numsSize - 1);//先翻转整个数组
partRotate(nums, 0, k - 1);//然后翻转前k - 1个
partRotate(nums, k, numsSize - 1);//最后翻转后numsSize - k个
}

边栏推荐
- Zhang Ping'an: accélérer l'innovation numérique dans le cloud et construire conjointement un écosystème industriel intelligent
- How MySQL uses JSON_ Extract() takes JSON value
- Machine learning 01: Introduction
- Oracle缩表空间的完整解决实例
- ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲
- Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
- CVPR 2022 best student paper: single image estimation object pose estimation in 3D space
- mysql5.6解析JSON字符串方式(支持复杂的嵌套格式)
- SQL删除重复数据的实例教程
- C#实现水晶报表绑定数据并实现打印3-二维码条形码
猜你喜欢

Rider 设置选中单词侧边高亮,去除警告建议高亮
一文了解MySQL事务隔离级别
MySQL queries the latest qualified data rows
SQL删除重复数据的实例教程

Rider set the highlighted side of the selected word, remove the warning and suggest highlighting

ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲

winedt常用快捷键 修改快捷键latex编译按钮

Beijing internal promotion | the machine learning group of Microsoft Research Asia recruits full-time researchers in nlp/ speech synthesis and other directions

Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition

查看自己电脑连接过的WiFi密码
随机推荐
How MySQL uses JSON_ Extract() takes JSON value
企业数字化发展中的六个安全陋习,每一个都很危险!
SQL Server(2)
IDEA 项目启动报错 Shorten the command line via JAR manifest or via a classpath file and rerun.
Mysql5.6 parsing JSON strings (supporting complex nested formats)
The comprehensive competitiveness of Huawei cloud native containers ranks first in China!
Check the WiFi password connected to your computer
Seven Devops practices to improve application performance
关于mysql中的json解析函数JSON_EXTRACT
Learn about MySQL transaction isolation level
力扣解法汇总729-我的日程安排表 I
33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)
Mongodb (quick start) (I)
thinkphp3.2.3
C#(Winform) 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
十个顶级自动化和编排工具
How to write a full score project document | acquisition technology
Debug kernel code through proc interface
解决“双击pdf文件,弹出”请安装evernote程序
IDC报告:腾讯云数据库稳居关系型数据库市场TOP 2!