Merge two array, arr1 and arr2, into arr1.
Sorted in nondecreased order.

input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
output: [1,2,2,3,5,6]

input: nums1 = [1], m = 1, nums2 = [], n = 0
output: [1]

input: nums1 = [0], m = 0, nums2 = [1], n = 1
output: [1]

理解

如果陣列二是空的,就不必檢查,直接回傳。
兩陣列是從小排到大,最後得到的陣列(在陣列一中排)也是從小排到大。
然後從最大的數開始排起,也就是從陣列一的最後看回來,
而且陣列一最後面的index是兩陣列大小總和減1(code裡len=m+n-1)。
比較大小並寫入陣列一中,陣列一中比較過的數,他的index(code裡的m)裡的值一定會被重新寫入,就算寫入的位置是原來的,還是會寫入。
如果陣列二還有沒被寫進陣列一的,就依序陣列二index(code裡的n)大到小直接寫入陣列一中,剛剛比較停留在陣列一中的index(code裡的len)。

code(cpp)


Reference

reference from java

problem link

leetcode