看板 Python 關於我們 聯絡資訊
感謝版上先前不吝嗇的給予協助, 目前卡在一個成功解出來的leetcode題目中某一行解法,網址如下: 我也會把題目直接貼上來給大家參考,我所使用的版本是python3 https://leetcode.com/problems/merge-sorted-array/ =====題目===== Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] ====我的解法==== class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ while m > 0 and n > 0: if nums2[n-1] > nums1[m-1] : nums1[m+n-1] = nums2[n-1] n -= 1 else: nums1[m+n-1] = nums1[m-1] nums1[m-1] = nums2[n-1] #line a #nums1[m-1] = nums1[m+n-1] #line b m -=1 if m==0 and n>0: nums1[:n] = nums2[:n] ====我的疑問(1/2)==== 在hashtag那邊有註解line a與b,自己使用了line a來得到答案,但網路資源提供 了另一種解法是使用line b來取代line a,這點就不大明白是如何運作的。 因此我在colab做了一個迴圈來檢視line b的行為,如下, ====Colab==== a = [1,2,3,0,0,0] n=5 b=0 while n > 0: a[n] = a[b] a[b] = a[n] n -=1 b +=1 print(a,n,b) ====Results==== [1, 2, 3, 0, 0, 1] 4 1 [1, 2, 3, 0, 2, 1] 3 2 [1, 2, 3, 3, 2, 1] 2 3 [1, 2, 3, 3, 2, 1] 1 4 [1, 2, 3, 3, 2, 1] 0 5 ====我的疑問(2/2)==== 如果line b是對的,在colab裡面,我預期得到的結果應該會是 [0, 0, 0, 3, 2, 1] ,但顯然的python3並不是這樣算的,在while迴圈裡面, list中被複寫前數值並不會在下一行被呼叫出來,而是直接地被覆蓋。 如果是這樣,那為什麼使用line b可以解決這題。 謝謝你們。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 192.94.35.2 (美國) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1582701490.A.664.html
aassdd926: 我不知道有沒有理解錯,有看到解法 line a line b 都 02/26 17:07
aassdd926: 沒有,line b 的部分,因為前一行已經換了數值,所以 02/26 17:07
aassdd926: 那行只是同數值互換 02/26 17:07
LZN: line a跟line b跟解答無關, 這兩行都不跑就已經是解答了 02/26 17:09
cuteSquirrel: 對,其實原本的寫法就是正確的了.不用額外加line ab 02/26 19:05
cuteSquirrel: 原本的寫法+範例測試輸入http://tpcg.io/RsGHU9SO 02/26 19:06
cuteSquirrel: 有點像在merge sort內部最後合併子序列的概念 02/26 19:15
sandy946727: 謝謝上面幾位細心的解答 02/27 00:38