Python solution but Time limited Exceeded, why?


  • 0
    O

    Class Solution(object):

    def singleNumber(self, nums):
        for i in nums:
            if nums.count(i)==1:
                return i

  • 0
    K

    Every time you call nums.count(i), python needs to iterate across the entire list nums.
    Since you are making this call within the loop for i in nums:, you are forcing python to iterate through the list n^2 times.
    This works for short inputs, but the larger your input list the longer it will take.

    Try to implement this by looping over the input list only one time.


  • 0

    class Solution(object):
    def singleNumber(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    words={}
    for k in nums:
    if k not in words:
    words[k]=1
    else:
    if words[k]==1:
    del words[k]
    return words.keys()[0]
    it's my solution by py,maybe it is not best way,but AC.


  • 0
    W

    @繁华1994 you're using extra memory


Log in to reply
 

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