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

本文深入解析了如何将两个已排序的数组A和B合并并排序的算法实现,提供了Python代码示例,展示了如何在不使用额外空间的情况下,通过直接修改数组A来完成任务。文章来源于LeetCode题目“Sorted Merge LCCI”,适合对数组操作和排序算法感兴趣的读者。
部署运行你感兴趣的模型镜像

题目描述:

  给定两个排序后的数组 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

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值