美文网首页
LintCode_chapter2_section12_merg

LintCode_chapter2_section12_merg

作者: 穆弋 | 来源:发表于2015-11-10 10:37 被阅读25次

coding = utf-8

'''
Created on 2015年11月10日

@author: SphinxW
'''
# 合并排序数组
#
# 合并两个排序的整数数组A和B变成一个新的数组。
# 样例
#
# 给出A=[1,2,3,4],B=[2,4,5,6],返回 [1,2,2,3,4,4,5,6]
# 挑战
#
# 你能否优化你的算法,如果其中一个数组很大而另一个数组很小?


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
        res = []

        while len(A) > 0 and len(B) > 0:
            thisA = A[0]
            thisB = B[0]
            if thisA < thisB:
                res.append(thisA)
                del A[0]
            else:
                res.append(thisB)
                del B[0]
        if len(A) == 0:
            res += B
        if len(B) == 0:
            res += A
        return res

相关文章

网友评论

      本文标题:LintCode_chapter2_section12_merg

      本文链接:https://www.haomeiwen.com/subject/ntlhhttx.html