[leetcode] 398. Random Pick Index @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/87807921

原题

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);

解法

使用字典, 键是nums中的数字, values是数字的索引列表, 然后使用random.choice从列表中随机选择一个index即可.

代码

class Solution:

    def __init__(self, nums: 'List[int]'):
        self.data = collections.defaultdict(list)
        for i, n in enumerate(nums):
            self.data[n].append(i)            

    def pick(self, target: 'int') -> 'int':
        return random.choice(self.data[target])

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.pick(target)

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/87807921
今日推荐