Re: [討論] leetcode 88. Merge Sorted Array

作者: sandy946727 (昭昭)   2020-02-27 00:47:46
感謝推文的鄉民,結論是不需要line a & b就可以得到答案,
我這邊也附上一個簡單得例子,
以及詳細過程供未來有需要的人參考。
====代碼====
nums1 = [1,2,3,0,0,0]
nums2 = [1,4,5] #這裡我故意讓index 0的數字小於nums1[2]
m=3
n=3
while m > 0 and n > 0:
if nums2[n-1] > nums1[m-1] :
nums1[m+n-1] = nums2[n-1]
n -= 1
print(nums1,"top,m,n:",m,n)
else:
nums1[m+n-1] = nums1[m-1]
m -=1
print(nums1,"bot,m,n:",m,n)
====結果====
[1, 2, 3, 0, 0, 5] top,m,n: 3 2
[1, 2, 3, 0, 4, 5] top,m,n: 3 1
[1, 2, 3, 3, 4, 5] bot,m,n: 2 1
^ ^ #這裡是把左邊的3向右推一格並取代0
[1, 2, 2, 3, 4, 5] bot,m,n: 1 1
^ ^ #這裡是把左邊的2向右邊推一格並取代3
[1, 1, 2, 3, 4, 5] bot,m,n: 0 1
^ #最終挪出一個空間讓nums2[0]填進去
※ 引述《sandy946727 (昭昭)》之銘言:
: 感謝版上先前不吝嗇的給予協助,
: 目前卡在一個成功解出來的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可以解決這題。
: 謝謝你們。

Links booklink

Contact Us: admin [ a t ] ucptt.com