Why I got the 'Time Limit Exceed'? for this simple python problem.


  • 0
    M

    '''
    Hi Everybody, This is my first time to work on leetcode. Here is my python code for the Single Number. Can anyone tell me why I got 'Time Limit Exceed'? I believe there is something wrong with the function initiation, But I do not know how to fix it.
    '''

    class Solution:
        # @param A, a list of integer
        # @return an integer
    
        def singleNumber(self, A):
            countItem = []
    
            for item in A:
                if item in countItem:
                    countItem.remove(item)
                else:
                    countItem.append(item)
    
            return(countItem)

  • 2
    R

    Your method is not a linear solution.
    Could python do the "search", "remove", "append" all in O(1) ?
    If not, then your solution is not a linear one;


  • 0
    R

    The remove method is linear because you are using a list so your algorithm is quadratic.
    The same for the operator in.
    You shouldmuse a set instead to have a O(n) or O(nlogN) dependig on the impl of the set.


  • 0
    B

    your return is a list ,not a integer


Log in to reply
 

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