首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: 88. Merge Sorted Array

leetcode: 88. Merge Sorted Array

作者头像
JNingWei
发布2018-09-27 16:24:05
3260
发布2018-09-27 16:24:05
举报
文章被收录于专栏:JNing的专栏JNing的专栏

Problem

# 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.

AC

class Solution():
    def merge(self, p, m, q, n):
        while m and n:
            if p[m-1] >= q[n-1]:
                p[m+n-1], m = p[m-1], m-1
            else:
                p[m+n-1], n = q[n-1], n-1
        while n:    # 如果是 n=0 而 m!=0,则p[:m]的部分已被排好,无需更改。
            p[n-1], n = q[n-1], n-1


if __name__ == "__main__":
    A = [1, 3, 5, 0, 0, 0, 0]
    B = [2, 4, 6, 7]
    Solution().merge(A, 3, B, 4)
    assert A == [1, 2, 3, 4, 5, 6, 7]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年11月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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