Table of Content
题目

解题思路
这道题比较简单,有两种解题思路:
解法一
遍历nums,记录索引位置,然后通过random.sample() 返回一个结果。(beats 50%)
解法二
计算目标在nums中的个数 e,然后通过random.randint(1, e) 随机选出“第i个”目标,然后在nums列表中顺序 “数数”,数到“第i个”目标就返回其索引。(beats 100%)
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
''' @auther: Jedi.L @Date: Wed, May 8, 2019 11:11 @Email: xiangyangan@gmail.com @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) |
我的GitHub : GitHub