題目介紹:
給定一個數組,将數組中的元素向右移動 k 個位置,其中 k 是非負數。
輸入: [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]
開始覺得這道題還挺簡單的,後來測試時出現了很多沒想到的測試結果,也是不斷地修改,不過總算通過了,Mark一下
小白用的最簡單的方法,最簡單的想法
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
result = list()
k=k%len(nums)
for i in range(len(nums) - k, len(nums)):
a = nums[i]
result.append(a)
for j in range(0, len(nums) - k):
b = nums[j]
result.append(b)
del nums[:]
for l in result:
nums.append(l)