Python solution but Time limited Exceeded, why?

  • 0

    Class Solution(object):

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

  • 0

    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
    for k in nums:
    if k not in words:
    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

    @繁华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.