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----苔原帶

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