LintCode Python 简单级题目 6.合并排序数组

原题描述:

合并两个排序的整数数组A和B变成一个新的数组。

样例

给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]

挑战 

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

题目分析:

合并两个排序的整数数组A和B变成一个新的数组。

 

源码:

class Solution:
    #@param A and B: sorted integer array A and B.
    #@return: A new sorted integer array
    def mergeSortedArray(self, A, B):
        # write your code here
        if A is None: return B
        if B is None: return A
        if len(A) > len(B):
            big,sma = A,B
        else:
            big,sma = B,A
        i = 0 
        while len(sma) > 0:
            n1 = sma[0]
            j = len(big)
            # i==j时,sma[0]元素已经比big[i-1]元素大,即big组最后一个元素
            # 执行insert会报索引超限,所以替换为使用append直到sma最后一个元素
            if i == j: 
                big.append(n1)
                sma.remove(sma[0])
            elif n1 <= big[i]: # sma[0]小于等于Big[i],在i位置插入,原Big[i]变为Big[i+1]
                big.insert(i,n1)
                sma.remove(sma[0])
            else: # sma[0]大于Big[i],继续查找Big下一个元素
                i += 1
        return big
原文地址:https://www.cnblogs.com/bozhou/p/6957426.html