Skip to content

Latest commit

 

History

History
93 lines (40 loc) · 1.41 KB

0398._Random_Pick_Index.md

File metadata and controls

93 lines (40 loc) · 1.41 KB

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

解题方案

思路 1 ******- 时间复杂度: O(N) init + O(1) pick - 空间复杂度: O(1)

O(N) init + O(1) pick

sb题没什么好说的, beats 52.52%

class Solution:

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.lookup = collections.defaultdict(list)
        for idx, num in enumerate(nums):
            self.lookup[num].append(idx)
            
        

    def pick(self, target):
        """
        :type target: int
        :rtype: int
        """
        idx = random.randrange(len(self.lookup[target]))
        return self.lookup[target][idx]