【发布时间】:2020-09-12 16:57:41
【问题描述】:
第一个问题是合并两个排序数组。为此,我使用了 2 指针方法。
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# two get pointers for nums1 and nums2
p1 = m - 1
p2 = n - 1
# set pointer for nums1
p = m + n - 1
# while there are still elements to compare
while p1 >= 0 and p2 >= 0:
if nums1[p1] < nums2[p2]:
nums1[p] = nums2[p2]
p2 -= 1
else:
nums1[p] = nums1[p1]
p1 -= 1
p -= 1
# add missing elements from nums2
nums1[:p2 + 1] = nums2[:p2 + 1]
上面的方法需要 O(n+m) 时间和 O(1) 空间,因为没有额外的复制到新数组,而是我们从最后开始覆盖 nums1,那里还没有信息。这样就不需要额外的空间了。
现在如果第一个数组太大而无法放入内存并且没有排序,那么输出一个排序后的数组怎么办?在这种情况下,解决方案会是什么样子?
【问题讨论】:
-
将未排序数组与排序数组“合并”意味着什么?结果应该排序吗?如果是这样,它几乎会归结为未排序数组的external sort,而排序后的数组主要是一种干扰。
-
是的,结果应该是排序的@user2357112supportsMonica
标签: python algorithm pointers data-structures merge