Skip to content

88. 合并两个有序数组 #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jotoy opened this issue Feb 17, 2020 · 0 comments
Open

88. 合并两个有序数组 #21

jotoy opened this issue Feb 17, 2020 · 0 comments

Comments

@jotoy
Copy link
Owner

jotoy commented Feb 17, 2020

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:
初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

解法:
归并排序的思想

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """        
        m = m-1
        n = n-1
        k = m+n+1
        while m>=0 or n>=0:
            if m>=0 and n>=0:
                if nums1[m]>=nums2[n]:
                    nums1[k] = nums1[m]
                    m-=1
                else:
                    nums1[k] = nums2[n]
                    n-=1
                k-=1
            if n<0 and m>=0:
                nums1[k] = nums1[m]
                m-=1
                k-=1
            if m<0 and n>=0:
                nums1[k] = nums2[n]
                n-=1
                k-=1
            
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant