LeetCode Merge Sorted Array

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.