Simple Pythonic solution


  • 0
    W
    import random
    
    class Solution(object):
    
        def __init__(self, nums):
            self.nums = nums
            
        def pick(self, target):
            choice, count = None, 0
            for i, n in enumerate(self.nums):
                if n == target:
                    count += 1
                    if random.randint(1, count) == 1:
                        choice = i
            return choice
    

Log in to reply
 

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