Test case always give the wrong answer


  • 0
    H

    The test case:
    Input: [0], 0, [1], 1
    expected output: [1]

    I ran my code on my IDE, it gives the right answer, but the test always says the output is: [1,0]

    Here is my code:

    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.
            """
            k = 0    # the length of the array
            i = 0    # the number of index in array 2
            while i!=len(nums2):
                if k == i+m:
                    nums1.insert(k,nums2[i])
                    i += 1
                elif nums2[i] < nums1[k]:
                    nums1.insert(k,nums2[i])
                    i += 1
                k += 1       
        
            nums1 = nums1[:m+n]+nums1[m+2*n:]
    

    Can someone help me figure it why?


  • 0

    @Hao_Ge Hint: Your last line is pointless, just creates a new list that immediately goes into the garbage. Don't know about the rest of the code, didn't read it.


  • -1
    F

    m+2*n is out of index of nums1. The result is different because different systems have different ways to handle out of index number.


  • 0

    @fisher5595 said in Test case always give the wrong answer:

    m+2*n is out of index of nums1.

    Maybe. Maybe not. But even if - so what?

    The result is different because different systems have different ways to handle out of index number.

    Nah. An out-of-bounds slice is simply empty.


  • 0
    F

    I see. The actual reason is re-assignment of the variable nums1 in the last line. It may work is nums1 is a global variable.


Log in to reply
 

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