398.leetcode题目讲解(Python):随机数索引(Random Pick Index)

题目

解题思路

这道题比较简单,有两种解题思路:

解法一

遍历nums,记录索引位置,然后通过random.sample() 返回一个结果。(beats 50%)

解法二

计算目标在nums中的个数 e,然后通过random.randint(1, e) 随机选出“第i个”目标,然后在nums列表中顺序 “数数”,数到“第i个”目标就返回其索引。(beats 100%)

参考代码

'''
@auther: Jedi.L
@Date: Wed, May 8, 2019 11:11
@Email: [email protected]
@Blog: www.tundrazone.com
'''

import random

# beats 100%
class Solution1:
    def __init__(self, nums):
        self.nums = nums

    def pick(self, target):
        e = self.nums.count(target)
        # ranodom select the i-th object 
        i = random.randint(1, e)
        # count 1 to i
        for j in range(len(self.nums)):
            if self.nums[j] == target:
                i = i - 1
                if i = 0:
                    return j

# beats 50%
class Solution2:
    def __init__(self, nums):
        self.nums = nums

    def pick(self, target):
        candid =[]
        for i in range(len(self.nums)):
            if self.nums[i] == target:
                candid.append(i)
        return random.sample(candid, 1)



如何刷题 : Leetcode 题目的正确打开方式

我的GitHub : GitHub

其他题目答案:leetcode题目答案讲解汇总(Python版 持续更新)

其他好东西: MyBlog----苔原带

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章