1. 程式人生 > >python leetcode 398. Random Pick Index

python leetcode 398. Random Pick Index

奇怪的是蓄水池抽樣演算法無法AC 程式碼2是蓄水池抽樣

class Solution(object):
    import random
    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.n=nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        res=[]
        
        for i in range(len(self.n)):
            if self.n[i]==target:
                res.append(i)
        return random.choice(res)
class Solution(object):
    import random
    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.n=nums

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        
        seed=0
        for i in range(len(self.n)):
            if self.n[i]==target:
                if random.randint(0,seed)==0:
                    res=i 
                    seed+=1
        return res