LintCode_chapter2_section12_merg

2015-11-10  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读