leetcode python3 简单题88. Merge Sorted Array

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第八十八题

(1)题目
英文:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

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

中文:
给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array

(2)解法
① 使用sort方法(先插入空位,再sort)
(耗时: 44ms,内存:13.6M)

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        for indx, num in enumerate(nums2):
            nums1[-len(nums2)+indx]=num
        nums1.sort()

注意:
1.本来想使用的是nums1=sorted(nums1),但是提交有报错,但是我在本地运行是无误的,这一点我不清楚是什么原因,有解决方案请Q我哦,THANKS。

② 使用双指针的方法

一种:(耗时:48ms,内存:13.7M)

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        temp = []
        p1 = 0
        p2 = 0
        while(p1<m and p2<n):
            if (nums1[p1]<=nums2[p2]):
                temp.append(nums1[p1])
                p1+=1
            else:
                temp.append(nums2[p2])
                p2+=1
        
        while(p1<m):
            temp.append(nums1[p1])
            p1 += 1
        while(p2<n):
            temp.append(nums2[p2])
            p2 += 1
        
        for i in range(0, m + n):
            nums1[i] = temp[i]

另一种:在本地能输出正确结果,但是提交会出错。有解决方案请Q我哦,THANKS。

class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        p = 0
        q = 0
        res = []
        while (p != m and q != n):
            if nums1[p] <= nums2[q]:
                res.append(nums1[p])
                p += 1
            else:
                res.append(nums2[q])
                q += 1
        if p < m:
            res.extend(nums1[p:-m])
        if q < n:
            res.extend(nums2[q:])
        nums1 = res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值