Why it work at OJ but not my own computer? ->IndexError: list assignment index out of range

  • 0

    Anyone could help me to solve this problem?

    nums1[end] = nums2[l2], IndexError: list assignment index out of range

    def merge(self, A, m, B, 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.
        l1, l2, end = m - 1, n - 1, m + n - 1
        while l1 >= 0 and l2 >= 0:
        	if nums2[l2] > nums1[l1]:
        		nums1[end] = nums2[l2]
        		l2 -= 1
        		nums1[end] = nums1[l1]
        		l1 -= 1
        	end -= 1
        if l1 < 0:
        	nums1[:l2 + 1] = nums2[:l2 + 1]

  • 0

    I am facing the same issue. Can anyone help us? Thanks in advance.

  • 0

    The notes of this question on Leetcode said

    "You may assume that nums1 has enough space (size that is greater or
    equal to m + n) to hold additional elements from nums2."

    When you run the code on your own computer, the input nums1 should be long enough. For example, you try call merge([1,2,3,4,9,0,0,0], 5, [5,6,7], 3), it works, the output is [1, 2, 3, 4, 5, 6, 7, 9]. Although the length of nums1 is 8(in order to hold all numbers from two arrays), m is still 5. So it works on your own computer if your input follows the Leetcode assume.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.