leetcode刷題--Rotate Array
題目:將包含n個元素的陣列向右旋轉k步,最好空間複雜度為O(1)
例如,陣列[1,2,3,4,5,6,7]包含元素個數n = 7,向右旋轉k = 3步,得到[5,6,7,1,2,3,4]。
我是不理解啥叫旋轉了,不過可以用平移。
最簡單版本程式碼:
class Solution:
# @param {integer[]} nums
# @param {integer} k
# @return {void} Do not return anything, modify nums in-place instead.
def rotate(self, nums, k):
n = len(nums)
if k > 0 and n > 1:
nums[:] = nums[n - k:] + nums[:n - k]
不過不滿足空間複雜度要求,因為開了新的空間存了個新list。
那怎麼改呢?
我們只有一個零時變數可用,要在原列表上得到新列表。
程式碼:
class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
n = len(nums)
idx = 0
distance = 0
cur = nums[0]
for x in range(n):
next = (idx + k) % n
temp = nums[next]
nums[next] = cur
idx = next
cur = temp
distance = (distance + k) % n
if distance == 0:
idx = (idx + 1) % n
cur = nums[idx]
這段程式碼來自http://bookshadow.com/weblog/2015/02/24/leetcode-rotate-array/主要是不理解啥事旋轉,就google搜了下,於是就被劇透了。。。
相關文章
- Rotate Array@LeetCodeLeetCode
- LeetCode-Rotate ArrayLeetCode
- 【LeetCode從零單排】No189 .Rotate ArrayLeetCode
- Leetcode Rotate ImageLeetCode
- Leetcode Rotate ListLeetCode
- LeetCode刷題整理LeetCode
- leetcode刷題(一)LeetCode
- LeetCode刷題 堆LeetCode
- LeetCode 刷題—樹LeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode-Rotate FunctionLeetCodeFunction
- Leetcode-Rotate ListLeetCode
- Leetcode-Rotate ImageLeetCode
- Rotate Image leetcode javaLeetCodeJava
- Rotate List leetcode javaLeetCodeJava
- LeetCode 刷題指南(一):為什麼要刷題LeetCode
- LeetCode 刷題筆記LeetCode筆記
- leetcode刷題筆記LeetCode筆記
- LeetCode刷題記錄LeetCode
- 如何使用leetcode刷題LeetCode
- leetcode刷題--Majority ElementLeetCode
- leetcode刷題--Count PrimesLeetCode
- leetcode刷題--Reverse BitsLeetCode
- leetcode刷題--Count and SayLeetCode
- Leetcode刷題分類LeetCode
- Leetcode刷題準備LeetCode
- LeetCode刷題—陣列LeetCode陣列
- [LeetCode] 61. Rotate ListLeetCode
- Leetcode 61. Rotate ListLeetCode
- 圖解:什麼是旋轉陣列(Rotate Array)?圖解陣列
- Leetcode刷題——求眾數LeetCode
- leetcode刷題筆記605LeetCode筆記
- Leetcode刷題系列彙總LeetCode
- leetcode刷題--Happy NumberLeetCodeAPP
- leetcode刷題--Number of 1 BitsLeetCode
- leetcode刷題記錄 661~LeetCode
- LeetCode刷題之第701題LeetCode
- Leetcode已刷題目題解彙總LeetCode