Python, Why using dictionary is accept but list not?


  • -1
    I

    why in method 2, i use dictionary is accepted, by in method 3, list gives run time error?

    class Solution:
        # @param {integer[]} nums
        # @return {boolean}
        def containsDuplicate(self, nums):
        
        #method 1
        #return len(set(nums))!=len(nums)
        
        # method 2
        dic={}
        for i in nums:
            if i in dic:
                return True
            dic[i]=1
        return False
        
        #method 3
        listt=[]
        for i in nums:
            if i in listt:
                return True
            listt.append(i)
        return False

  • 0

    This only runtime error here is the indentation error, and method 2 isn't accepted, either.


  • 2
    G

    In method 3, the if condition if i in listt actually takes O(n) time complexity to process in the worst case. Thus, method 3 is O(n^2). However, method 2 is O(cn).


Log in to reply
 

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