# 88 Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal tom+n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Concept:

1 3 5 6

2 4 7 9 -> pick 9

1 3 5 6

2 4 7 9 -> pick 7

1 3 5 6 -> pick 6

2 4 7 9

從nums1的m+n-1格開始放,

從nums1和nums2的尾巴開始讀,

i指針指向nums1,j指針指向nums2,

比較nums1[i]和nums2[j],把數字大的放到nums1的尾巴,並把該index--,

終止條件是nums1或nums2已經讀到0。

最後nums2如果還有剩餘的,再依序放入nums1。

Pseudocode:

int k=m+n-1 -> index for final nums1
int i=m-1, j=n-1; -> index for nums1 and nums2
while i>=0 and j>=0
    nums1[k--] = nums1[i] > nums2[j] ? nums1[i--] : nums2[j--]
while j>=0
    nums1[k--] = nums2[j--]

這題pseudocode跟完整程式碼差不多...

results matching ""

    No results matching ""