美文网首页leetcode题解
【Leetcode】88—Merge Sorted Array

【Leetcode】88—Merge Sorted Array

作者: Gaoyt__ | 来源:发表于2019-07-20 17:49 被阅读0次
    一、题目描述

    给定两个有序整数数组 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]
    
    二、代码实现

    因为要将合并后的数组放在nums1中,因此采用从后向前合并的方式。

    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.
            """
            index = m + n -1
            while m>0 and n>0:
                if nums1[m-1] > nums2[n-1]: 
                    nums1[index] = nums1[m-1]
                    m = m - 1
                else:
                    nums1[index] = nums2[n-1]
                    n = n - 1
                index = index - 1
            if n > 0: nums1[0:n] = nums2[0:n]
    

    相关文章

      网友评论

        本文标题:【Leetcode】88—Merge Sorted Array

        本文链接:https://www.haomeiwen.com/subject/hjvulctx.html