[Title] 88. LeetCode brush merge two ordered arrays

Given two ordered arrays of integers and nums2 nums1, incorporated into the nums2 nums1 in an ordered array such as a num1.

Description:

And initializing the number of elements nums1 nums2 of m and n.
You can assume nums1 sufficient space (space equal to or greater than m + n) to save the elements of nums2.

method one:

Double pointer method, traversing two arrays, one by one from front to back comparison add, require auxiliary space;

The time complexity of O (m + n), the spatial complexity of O (m)

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: None Do not return anything, modify nums1 in-place instead.
        """
        copy_num1 = nums1[:m]
        nums1[:] = []

        # 双指针
        p1 = 0
        p2 = 0

        while p1 < m and p2 < n:
            if copy_num1[p1] < nums2[p2]:
                nums1.append(copy_num1[p1])
                p1 += 1
            else:
                nums1.append(nums2[p2])
                p2 += 1
        if p1 < m:
            nums1[p1 + p2:] = copy_num1[p1:]
        if p2 < n:
            nums1[p1 + p2:] = nums2[p2:]

a = Solution()
num1 = [ 1,2,3,0,0,0]
m=3
n=3
num2=[2,5,6]
a.merge(num1,m,num2,n)
print(num1)

Method Two:

In the method a more optimized by topic shows that we can from the back to add from large to small in num1 array. Without auxiliary space.

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: None Do not return anything, modify nums1 in-place instead.
        """
        # 双指针
        p1 = m - 1
        p2 = n - 1
        k = m + n - 1

        while p1 >= 0 and p2 >= 0:
            if nums1[p1] < nums2[p2]:
                nums1[k] = nums2[p2]
                p2 -= 1
            else:
                nums1[k] = nums1[p1]
                p1 -= 1
            k -= 1

        # m<n,加入num2剩余元素
        nums1[:p2+1] = nums2[:p2+1]

a = Solution()
num1 = [ 1,2,3,0,0,0]
m=3
n=3
num2=[2,5,6]
a.merge(num1,m,num2,n)
print(num1)

 

 

Published 83 original articles · won praise 14 · views 30000 +

Guess you like

Origin blog.csdn.net/weixin_38121168/article/details/103427342