快乐的LeetCode --- 合并排序的数组

题目描述:

  给定两个排序后的数组 A 和 B,其中 A 的末端有足够的缓冲空间容纳 B。 编写一个方法,将 B 合并入 A 并排序。

初始化 A 和 B 的元素数量分别为 m 和 n。

示例:

输入:
A = [1,2,3,0,0,0], m = 3
B = [2,5,6],       n = 3

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

解题思路1:

  1. 当数组A的元素下标大于A元素的数量m时,将数组B的元素依次赋值给A后面的位置。
  2. 返回排序

代码1:

class Solution(object):
    def merge(self, A, m, B, n):
        """
        :type A: List[int]
        :type m: int
        :type B: List[int]
        :type n: int
        :rtype: None Do not return anything, modify A in-place instead.
        """
        i = 0
        for index, num in enumerate(A):
            if index > m-1 and i < n:
                A[index] = B[i]
                i += 1

        return sorted(A)

结果为: [1, 2, 2, 3, 5, 6]


class Solution(object):
    def merge(self, A, m, B, n):
        """
        :type A: List[int]
        :type m: int
        :type B: List[int]
        :type n: int
        :rtype: None Do not return anything, modify A in-place instead.
        """
        for index in range(n):
            A[m + index] = B[index]
        A = sorted(A)
        return A

s = Solution()
A = [1, 2, 3, 0, 0, 0]
B = [2, 5, 6]
m = 3
n = 3
print(s.merge(A, m, B, n))

注意:

在leetcode编译栏中,输入的正确代码形式应该是:

class Solution(object):
    def merge(self, A, m, B, n):
        """
        :type A: List[int]
        :type m: int
        :type B: List[int]
        :type n: int
        :rtype: None Do not return anything, modify A in-place instead.
        """
        i = 0
        for index, num in enumerate(A):
            if index > m-1 and i < n:
                A[index] = B[i]
                i += 1
        
        A.sort()

特别注意返回值的写法!


题目来源: https://leetcode-cn.com/problems/sorted-merge-lcci

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值