LintCode_chapter2_section12_merge-sorted-array-ii

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容