Python合并两个有序数组

[本文出自天外归云的博客园]

问题:合并两个有序数组

思路:双指针挨个比较两个数组的元素

代码如下:

#!/usr/bin/python

def combine_two_sorted_arr(a, b):
    c = []
    i, j = 0, 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            c.append(a[i])
            i += 1
        else:
            c.append(b[j])
            j += 1
    if i == len(a):
        c += b[j:]
    elif j == len(b):
        c += a[i:]
    return c

a = [1, 2, 3, 5, 6, 7, 8, 10]
b = [2, 3, 4, 5, 8, 9]
c = combine_two_sorted_arr(a, b)
print(c)

 

posted @ 2022-06-28 16:29  天外归云  阅读(132)  评论(0编辑  收藏  举报