[本文出自天外归云的博客园]
问题:合并两个有序数组
思路:双指针挨个比较两个数组的元素
代码如下:
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)