版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28266311/article/details/82989389
题目
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入:[1,2,3,4,5,6,7]和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步:[7,1,2,3,4,5,6] 向右旋转 2 步:[6,7,1,2,3,4,5] 向右旋转 3 步:[5,6,7,1,2,3,4]
示例 2:
输入:[-1,-100,3,99]和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100]
说明:
- 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
- 要求使用空间复杂度为 O(1) 的原地算法。
python代码实现:
方法一:
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
if k == 0 or len(nums) < 2:
return
length = len(nums)
n, i, j = 0, 0, 0
temp1 = nums[0]
while n < length:
j = (j + k) % length
temp2 = nums[j]
nums[j] = temp1
temp1 = temp2
if i == j:
i = (i + 1) % length
j = i
temp1 = nums[i]
n += 1
方法二:
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
l = len(nums)
k %= l
k1 = l - k
if k != 0:
for i in range((k1 - 1) // 2 + 1):
t1 = nums[i]
nums[i] = nums[k1 - 1 - i]
nums[k1 - 1 - i] = t1
for j in range(k1,(k1 + l - 1) // 2 + 1):
t2 = nums[j]
nums[j] = nums[l - 1 + k1 - j]
nums[l - 1 + k1 - j] = t2
nums.reverse()