当前位置:网站首页>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个
}
边栏推荐
- Matery主题自定义(一)黑夜模式
- MySQL queries the latest qualified data rows
- 漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
- Cartoon: how to multiply large integers? (I) revised version
- Tita 绩效宝:如何为年中考核做准备?
- Abnormal recovery of virtual machine Oracle -- Xi Fenfei
- 中国银河证券开户安全吗 开户后多久能买股票
- 一文了解Go语言中的函数与方法的用法
- WebApp开发-Google官方教程
- 云主机oracle异常恢复----惜分飞
猜你喜欢
Machine learning 01: Introduction
Summary of optimization scheme for implementing delay queue based on redis
MYSQL group by 有哪些注意事项
Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition
漏洞复现----48、Airflow dag中的命令注入(CVE-2020-11978)
VBA驱动SAP GUI实现办公自动化(二):判断元素是否存在
Knowledge points of MySQL (6)
How to write a full score project document | acquisition technology
Tips for extracting JSON fields from MySQL
网络威胁分析师应该具备的十种能力
随机推荐
SQL Server(2)
一文了解MySQL事务隔离级别
Machine learning 02: model evaluation
漫画:寻找股票买入卖出的最佳时机
[7.7 live broadcast preview] the lecturer of "typical architecture of SaaS cloud native applications" teaches you to easily build cloud native SaaS applications. Once the problem is solved, Huawei's s
stirring! 2022 open atom global open source summit registration is hot!
求解为啥all(())是True, 而any(())是FALSE?
What are the precautions for MySQL group by
基于Redis实现延时队列的优化方案小结
mongodb(快速上手)(一)
数据访问 - EntityFramework集成
如何修改mysql字段为自增长字段
Learn about MySQL transaction isolation level
普通程序员看代码,顶级程序员看趋势
Redis+caffeine two-level cache enables smooth access speed
Count the running time of PHP program and set the maximum running time of PHP
力扣解法汇总1200-最小绝对差
WR | Jufeng group of West Lake University revealed the impact of microplastics pollution on the flora and denitrification function of constructed wetlands
Beijing internal promotion | the machine learning group of Microsoft Research Asia recruits full-time researchers in nlp/ speech synthesis and other directions
提高应用程序性能的7个DevOps实践