簡體   English   中英

為什么這個解決方案不適合“旋轉數組”leetcode 問題?

[英]Why is this solution not ideal for “Rotate Array” leetcode question?

leetcode 上的問題是“給定一個數組,將數組向右旋轉 k 步,其中 k 是非負數。” 例如“輸入:nums = [1,2,3,4,5,6,7],k = 3 Output:[5,6,7,1,2,3,4]”

我在 python 中的解決方案是:

def rotate(self, nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: None Do not return anything, modify nums in-place instead.
    """
    i = 0
    while (i < k):
        nums.insert(0, nums.pop())
        i+=1

這似乎與任何給定的解決方案都不匹配。 我很好奇這會是什么時間/空間復雜度? 這就是為什么這不是一個給定的解決方案嗎? 或者在技術面試中最好不要使用數組函數?

謝謝

以下是 python 中的cut清單示例,不確定這是否是您正在尋找的解決方案。 您將索引k處的列表帶到列表的length 因此,在這種情況下,它的3 to 6並且您將列表的開頭0 to 2並且您獲取列表的第一部分並將其添加到列表的末尾k的數量。

nums[k:length] = [4,5,6,7]
nums[0:k] = [1,2,3]`
def rotate(nums, k):
    
    length = len(nums)
    nums[:] = nums[k:length] + nums[0:k]
    print(nums)
        
number = [1,2,3,4,5,6,7]
rotate(number,3)

這是指向其他一些解釋的鏈接。

https://www.geeksforgeeks.org/python-program-for-program-for-array-rotation-2/

insert將為每次迭代在內部將所有后續的 n-1 個元素復制 1。 因此,正如 Paul 所說,您的代碼具有 O(nk) 的時間復雜度。 因此,即使它回答了問題,但對於大型陣列來說效率太低了。 相反,您可以使用時間復雜度 O(N) 的數組切片。

def rotate_to_right(nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: None Do not return anything, modify nums in-place instead.
    """
    d = len(nums) - k
    nums[:]=nums[d:]+nums[:d]

if __name__ == '__main__':
    nums = [1,2,3,4,5,6,7]
    k = 3
    rotate_to_right(nums, k)
    print(nums)

結果:

[5, 6, 7, 1, 2, 3, 4]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM