題目:
給定一個數組,將數組中的元素向右移動 k 個位置,其中 k 是非負數。
說明:
- 盡可能想出更多的解決方案,至少有三種不同的方法可以解決這個問題。
- 要求使用空間復雜度為 O(1) 的 原地 算法。
思路:
本題思路簡單。
程序:
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
length = len(nums)
if k == 0:
return
index = k
target = length - 1
while k > 0:
data = nums[target]
nums.insert(0,nums.pop())
k -= 1