【问题标题】:Merge Two Arrays, one is sorted and the other one is not and the second doesn't fit into memory [Python]合并两个数组,一个已排序,另一个未排序,第二个不适合内存 [Python]
【发布时间】: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


【解决方案1】:

外部排序应该按照评论中的建议解决这个问题。

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 2018-04-17
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    相关资源
    最近更新 更多