398. Random Pick Index
Medium
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
题目大意:给定一个数组,要求编写一个数据结构,能随机地从数组中返回一个元素,元素值指定。
解题思路:利用python内置的random.choice()方法。
from random import choice
class Solution:
def __init__(self, nums: List[int]):
self.nums = nums
self.size = len(nums)
def pick(self, target: int) -> int:
idx_lst = [] #store idx of target
for i in range(self.size):
if self.nums[i] == target:
idx_lst.append(i)
if len(idx_lst) == 0: #input assumption if incorrect
raise ValueError
return choice(idx_lst) #choose one of the index randomly
# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)
测试一下,
Success
[Details]
Runtime: 80 ms, faster than 85.87% of Python3 online submissions for Random Pick Index.
Memory Usage: 15.4 MB, less than 66.01% of Python3 online submissions for Random Pick Index.