在leetcode中合并排序数组

时间:2018-02-04 06:01:39

标签: python arrays sorting

我在https://leetcode.com/problems/merge-sorted-array/description/https://leetcode.com/problems/merge-sorted-array/discuss/29503/Beautiful-Python-Solution

中看到了这个
def merge(self, nums1, m, nums2, n):
        while m > 0 and n > 0:
            if nums1[m-1] >= nums2[n-1]:
                nums1[m+n-1] = nums1[m-1]
                m -= 1
            else:
                nums1[m+n-1] = nums2[n-1]
                n -= 1
        if n > 0:
            nums1[:n] = nums2[:n]

我有两个疑问:

  1. 当我想运行代码print(Solution().merge([1, 2, 3], 3, [4, 5, 6], 3))时,它只是给了我一个错误提示IndexError: list assignment index out of range
  2. 我不太清楚上面答案中的方法。 有人能告诉我如何解决这类问题吗?

2 个答案:

答案 0 :(得分:1)

问题在于:

def merge(self, nums1, m, nums2, n):
    while m > 0 and n > 0:
        if nums1[m-1] >= nums2[n-1]:
            nums1[m+n-1] = nums1[m-1]   # nums1[m+n-1] IndexError
            m -= 1
        else:
            nums1[m+n-1] = nums2[n-1]   # Same as above
            n -= 1
    if n > 0:
        nums1[:n] = nums2[:n]

您可能希望首先“调整”列表大小以防止索引错误:

def merge(self, nums1, m, nums2, n):
    nums1 += nums2
    # Or nums1 += [None] * len(nums2)

    while m > 0 and n > 0:
        if nums1[m-1] >= nums2[n-1]:
            nums1[m+n-1] = nums1[m-1] # nums1[m+n-1] IndexError
            m -= 1
        else:
            nums1[m+n-1] = nums2[n-1] # Same as above
            n -= 1
    if n > 0:
        nums1[:n] = nums2[:n]

答案 1 :(得分:0)

def merge_two_sorted_arrays(left: list, right: list) -> list:
    """
    Merge Sorted Array in leetcode
    Args:
        left: left array
        right: right array

    Returns: A new merged array
    """
    A = [None] * (len(left) + len(right))
    i = j = k = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            A[k] = left[i]
            i += 1
        else:
            A[k] = right[j]
            j += 1
        k += 1
    while i < len(left):
        A[k] = left[i]
        i += 1
        k += 1
    while j < len(right):
        A[k] = right[j]
        j += 1
        k += 1

    return A


a = [1, 2, 2, 4]
b = [3, 5, 6, 9]

print(merge_two_sorted_arrays(a, b))

输出:

[1, 2, 2, 3, 4, 5, 6, 9]