leetcode 面试题 10.01. Sorted Merge LCCI 合并排序的数组 双指针

leetcode 面试题 10.01. Sorted Merge LCCI 合并排序的数组 双指针

leetcode 2020年3月 每日一题打卡
程序员面试金典

题目: 给定两个排序后的数组 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]
说明:A.length == n + m

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

思路: python :最简单的办法是把B放到A中,再排序A。第二种方法就是利用A和B已经排好序的条件,采用双指针

细节: 这道题的返回值是数组A所以要把数组ans深复制到A中:A[:]=ans

代码:

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.
        """
        # 双指针
        pa=0
        pb=0
        ans=[]
        while not(pa==m and pb==n):
            if pa == m:
                ans.append(B[pb])
                pb+=1
                continue
            if pb == n:
                ans.append(A[pa])
                pa+=1
                continue
            if A[pa]>B[pb]:
                ans.append(B[pb])
                pb+=1
                continue
            if A[pa]<B[pb]:
                ans.append(A[pa])
                pa+=1
                continue
            if A[pa]==B[pb]:
                ans.append(A[pa])
                ans.append(B[pb])
                pa+=1
                pb+=1
                continue
              
        A[:]=ans
        return A

本博客为原创作品,欢迎指导,转载请说明出处,附上本文链接,谢谢

发布了20 篇原创文章 · 获赞 1 · 访问量 205

猜你喜欢

转载自blog.csdn.net/weixin_43973433/article/details/104860539
今日推荐