Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input:[1,2,3,4,5,6,7]and k = 3 Output:[5,6,7,1,2,3,4]Explanation: rotate 1 steps to the right:[7,1,2,3,4,5,6]rotate 2 steps to the right:[6,7,1,2,3,4,5]rotate 3 steps to the right:[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
k非负。k=0就返回原来的列表。
k>0,列表后面接上原来的一个列表,然后可以截取索引k+1到最后一个,然后返回。但是空间复杂度不是1.
另一种方法:
1234567
7234561
7134562
7124563
7123564
7123465
7123456
利用一个temp和列表最后一个元素,来进行交换。
超时了~!!!!!
想想还有什么改进的方法?
5674123
直接倒数三个一起跟前面换。但是空间复杂度又高了。
倒数第k个跟nums[0]换,倒数第一个跟nums【k-1】换,然后除去前k个,然后剩下的再进行这样的操作。
结果忘记考虑,k>len(nums)的情况,其实这种情况一定跟其中一种k<len(nums)的情况一样。取余就可以

边界弄错了~
discuss:
太机智了

python 版本

时间复杂度 O(N) N 是list长度
本文探讨了数组右旋的具体实现方法,并提供了几种不同的解决方案。通过实例演示了如何将数组向右旋转k步,包括直接旋转和使用临时变量等方法。
377

被折叠的 条评论
为什么被折叠?



