zoukankan      html  css  js  c++  java
  • 6. 合并排序数组 II

    6. 合并排序数组 II

    中文English

    合并两个有序升序的整数数组A和B变成一个新的数组。新数组也要有序。

    样例

    样例 1:

    输入: A=[1], B=[1]
    输出:[1,1]	
    样例解释: 返回合并后的数组。
    

    样例 2:

    输入: A=[1,2,3,4], B=[2,4,5,6]
    输出: [1,2,2,3,4,4,5,6]	
    样例解释: 返回合并后的数组。
    

    挑战

    你能否优化你的算法,如果其中一个数组很大而另一个数组很小? 

    输入测试数据 (每行一个参数)如何理解测试数据?

    双指针 + 背向取最大

    class Solution:
        """
        @param A: sorted integer array A
        @param B: sorted integer array B
        @return: A new sorted integer array
        """
        def mergeSortedArray(self, A, B):
            # write your code here
            #双指针解法,时间复杂度O()数组小的那个长度
            
            results = []
            point_A, point_B = len(A) - 1, len(B) - 1 
            
            #循环指针
            while point_A >= 0 and point_B >= 0:
                #判断大小
                if (A[point_A] > B[point_B]):
                    results.insert(0, A[point_A])
                    point_A -= 1
                else:
                    results.insert(0, B[point_B])
                    point_B -= 1 
            
            #最后直接加进来,看哪个没有走完
            if (point_A != -1):
                #注意,指针指向问题,poion_A + 1,最后一个poion_A是没有走完的,所以需要加进来
                results = A[: point_A + 1] + results
            else:
                results = B[: point_B + 1] + results
            
            return results

     双指针 + 正向 (每次取最小)

    class Solution:
        """
        @param A: sorted integer array A
        @param B: sorted integer array B
        @return: A new sorted integer array
        """
        def mergeSortedArray(self, A, B):
            # write your code here
            #双指针写法,每次取最小
            
            results = []
            point_A, point_B = 0, 0
            m, n = len(A), len(B)
            
            while point_A < m and point_B < n:
                if (A[point_A] < B[point_B]):
                    results.append(A[point_A])
                    point_A += 1 
                else:
                    results.append(B[point_B])
                    point_B += 1 
            
            #最终判断
            if (point_A != m):
                results.extend(A[point_A: ])
            else:
                results.extend(B[point_B: ])
            
            return results
                
                
  • 相关阅读:
    shell 基础进阶 *金字塔
    shell,awk两种方法写9*9乘法表
    shell脚本判断一个用户是否登录成功
    shell 冒泡算法 解决数组排序问题
    shell 石头剪刀布
    应用shell (ssh)远程链接主机
    nmcli命令使用
    光盘yum源autofs按需挂载
    LVM扩容,删除
    LVM创建
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13462830.html
Copyright © 2011-2022 走看看