当前位置:网站首页>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个
}

边栏推荐
猜你喜欢
MYSQL group by 有哪些注意事项

统计php程序运行时间及设置PHP最长运行时间
Example tutorial of SQL deduplication
深入理解Redis内存淘汰策略

Which is more cost-effective, haqu K1 or haqu H1? Who is more worth starting with?

33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)

How to write a full score project document | acquisition technology

Oracle Recovery Tools ----oracle数据库恢复利器

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

C # mixed graphics and text, written to the database in binary mode
随机推荐
Knowing that his daughter was molested, the 35 year old man beat the other party to minor injury level 2, and the court decided not to sue
Tita performance treasure: how to prepare for the mid year examination?
Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
外盘黄金哪个平台正规安全,怎么辨别?
云主机oracle异常恢复----惜分飞
得知女儿被猥亵,35岁男子将对方打至轻伤二级,法院作出不起诉决定
Is it safe for China Galaxy Securities to open an account? How long can I buy stocks after opening an account
哈趣K1和哈趣H1哪个性价比更高?谁更值得入手?
C#(Winform) 当前线程不在单线程单元中,因此无法实例化 ActiveX 控件
Ordinary programmers look at the code, and top programmers look at the trend
Cartoon: how to multiply large integers? (next)
求解为啥all(())是True, 而any(())是FALSE?
Machine learning 02: model evaluation
MySQL queries the latest qualified data rows
Understand the usage of functions and methods in go language
如何保存训练好的神经网络模型(pytorch版本)
Abnormal recovery of virtual machine Oracle -- Xi Fenfei
Cartoon: how to multiply large integers? (integrated version)
Server configuration jupyter environment
The comprehensive competitiveness of Huawei cloud native containers ranks first in China!