1 流程
假设有序数组是按照升序排序,则归并这两个有序数组的步骤如下:
- 分别对比两边最左侧的数值,则选取这两个数值中的最小值移出
- 重复上述步骤直至所有元素全部移出。
合并两个有序数组[1,3,5]
和[2,4]
的流程如图所示:
2 时间复杂度分析
假设两个数组的长度分别为n
和m
,因为最终通过比较得到了一个长度n+m
的数组,不难得到时间复杂度为O(n+m)
.
以上图为例,长度为3
和长度为2
的数组,每一步的流程对比如下所示:
- 1 < 2
- 3 > 2
- 3 < 4
- 5 > 4
- 5
可以看出总共执行了3+2=5
次。
3 Python实现
nums1 = [1,3,5]
nums2 = [2,4]
big_nums = []
while nums1 or nums2:
t1 = t2 = 1e6
if nums1:
t1 = nums1[0]
else:
big_nums.extend(nums2)
break
if nums2:
t2 = nums2[0]
else:
big_nums.extend(nums1)
break
if t1 < t2:
big_nums.append(nums1.pop(0))
else:
big_nums.append(nums2.pop(0))
print(big_nums)