Why my local code get diffrent answer from OJ system.


  • 0
    C

    here is my code:

    class Solution:
        # @param A  a list of integers
        # @param m  an integer, length of A
        # @param B  a list of integers
        # @param n  an integer, length of B
        # @return nothing
        def merge(self, A, m, B, n):
            i = 0
            j = 0
            while i < m and n > 0:
                if A[i]<B[j]:
                    while i < m and A[i] < B[j]:
                        i+=1
                    A.insert(i, B.pop(j))
                    n-=1
                    m+=1
                else:
                    while n > 0 and A[i] >= B[j]:
                        A.insert(i, B.pop(j))
                        n-=1
                        m+=1
            while len(B) > 0:
                *A.insert( m + n - len(B) , B.pop(0))*  # changed from A.append(B.pop(0))
            return
    
    if __name__ == '__main__':
        s = Solution()
        A,B = [], [1]
        s.merge(A,len(A),B,len(B))
        print A
    

    i submit my code to OJ, but here are results:

    Submission Result: Wrong Answer
    Input: 	[], [1]
    Output: 	[0]
    Expected: 	[1]
    

    i can't figure out why my code output [0] at this situation.
    So, could anyone point out my error in code, MANY THX.



  • 1
    M

    The problem is a difference between how you pass in A and B, and how leetcode does. As an artifact of the Java and C++ versions, the lists are assumed to be fixed in size, so while A is described as the empty list, it actually is the empty list followed by B.length 0s. The numbers m and n refer to the size of the described array, so A.length = m+n.

    In the case you have presented, A=[0], m=0, B=[1], and n=1. These are the values actually passed into your function. i=0 < m is false, so the while loop is skipped, and then you append B onto A, resulting in A=[0,1]. Since leetcode knows the length of the expected array, it only looks at the first n+m=1 elements, or [0].


  • 0
    C

    Got it ,thanks a loooooooooooooot for your explanation : )

    I modify my code by your instruction and got accpeted


Log in to reply
 

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