旋轉數組
阿新 • • 發佈:2018-05-13
其中 可能 in-place elf ret col 方法 AD 右移
給定一個數組,將數組中的元素向右移動 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) 的原地算法。
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
旋轉數組