给定一个数组,将数组中的元素向右移动 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]
解法一:开辟新的数组
n = len(nums)
Array = [0]*n
for i in range(n):
Array[(i+k)%n] = nums[i]
nums[:]=Array
解法二插入法
k = k%len(nums)
for i in range(k):
nums.insert(0,nums.pop())
解法三数组翻转
nums[:] = nums[::-1]
nums[:k] = nums[:k][::-1]
nums[k:][:] = nums[k:][::-1]
补充:双指针反转数组
def Reverse(nums):
left = 0
right = len(nums)-1
while left<right:
nums[left],nums[right] = nums[right],nums[left]
left+=1
right+=1
解法四
def gcd(m, n):
if m > n:
m, n = n, m
while m > 0:
mod = n % m
n, m = m, mod
return n
n = len(nums)
count = gcd(n, k)
for i in range(count):
cur = i
prev = nums[i]
while True:
last = (cur + k) % n
temp = nums[last]
nums[last] = prev
#prev记录上一个元素
prev = temp
cur = last
if cur == i:
break