前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q88 Merge Sorted Array

Q88 Merge Sorted Array

作者头像
echobingo
发布2018-04-25 16:46:40
6110
发布2018-04-25 16:46:40
举报

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

解题思路:

这题已经告诉nums1有足够的空间,因此可以利用这多余的空间做文章。

从nums1和nums2最大的元素开始比较,依次安排到nums1多余的空间中。如果nums2最后还存在比nums1中小的数字,则把nums2中剩余的数字依次放到nums1中。

Python实现:
代码语言:javascript
复制
class Solution:
    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.
        """
        i = m - 1; j = n - 1 
        k = m + n - 1
        while i >= 0 and j >= 0:  # 从大到小,把大的元素依次移到后面
            if nums1[i] < nums2[j]:
                nums1[k] = nums2[j]
                j -= 1
            else:  # 否则,把nums1中的元素后移一位
                nums1[k] = nums1[i]
                i -= 1
            k -= 1
        while j >= 0:  # 如果nums2中存在比nums1最小数字还要小的数字,则依次加入到nums1中
            nums1[k] = nums2[j]
            k -= 1
            j -= 1
        return

a = [1,2,4,5,6,-1]  # 用 -1 表示占位,即多余的空间
m = 5
b = [3]
n = 1
c = Solution()
print(c.merge(a,m,b,n))  # [1,2,3,4,5,6]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档