LeetCode Merge Sorted Array
LeetCode-solving-Merge Sorted Array
Original question
Combine Two ordered arrays into one.
Note:
The first array has enough space to store the elements in the second array. The valid length of the first array is m, and the valid length of the second array is n, which is modified on the original array without returning values.
Example:
Input: nums1 = [1, 1, 2, 2, 4, 0, 0, 0], m = 5, nums2 = [0, 0, 2, 3], n = 4
Output: none (nums1 becomes [0, 0, 1, 1, 2, 2, 2, 3, 4])
Solutions
Knowing the original length of the two arrays, you can know the merged length, traverse the two arrays in flashback, and place the large numbers first at the corresponding subscript of the merged array. If the first array is traversed, copy the remaining elements of the second array. If the second array is traversed first, no changes are required, because the remaining elements of the first array are already in the target position.
AC Source Code
class Solution(object): def merge(self, nums1, m, nums2, n): """ :type nums1: List[int] :type m: int :type nums2: List[int] :type n: int :rtype: void Do not return anything, modify nums1 in-place instead. """ index = m + n - 1 m -= 1 n -= 1 while m >= 0 and n >= 0: if nums1[m] > nums2[n]: nums1[index] = nums1[m] m -= 1 else: nums1[index] = nums2[n] n -= 1 index -= 1 if m < 0: nums1[:n + 1] = nums2[:n + 1]if __name__ == "__main__": num1 = [1, 1, 2, 2, 4, 0, 0, 0, 0] num2 = [0, 0, 2, 3] Solution().merge(num1, 5, num2, 4) assert num1 == [0, 0, 1, 1, 2, 2, 2, 3, 4]