# 398. Random Pick Index

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/random-pick-index/

> 内容描述

```
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%


```python
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]
```






























