Python AC solution using dictionary


  • 0
    D
    import random
    class Solution(object):
    
        def __init__(self, nums):
            self.num_dict={}
            i=0
            while i<len(nums):
                if nums[i] in self.num_dict:
                    self.num_dict[nums[i]].append(i)
                else:
                    self.num_dict[nums[i]]= [i]
                i+=1
            
    
        def pick(self, target):
            length=len(self.num_dict[target])
            if length==1:
                return self.num_dict[target][0]
            else:
                return self.num_dict[target][random.randint(0,length-1)]
                
    

  • 0
    A

    @dreamer92 said in Python AC solution using dictionary:

    import random
    class Solution(object):

    def __init__(self, nums):
        self.num_dict={}
        i=0
        while i<len(nums):
            if nums[i] in self.num_dict:
                self.num_dict[nums[i]].append(i)
            else:
                self.num_dict[nums[i]]= [i]
            i+=1
        
    
    def pick(self, target):
        length=len(self.num_dict[target])
        if length==1:
            return self.num_dict[target][0]
        else:
            return self.num_dict[target][random.randint(0,length-1)]
    

    This kind of answer now causes Memory Limit Exceeded error. Can't be Accepted.
    Mine is similar to yours. :(


Log in to reply
 

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