Skip to content

Commit c47e3c6

Browse files
committed
398
1 parent cc0ba80 commit c47e3c6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

RS/398.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## 398 Random Pick Index
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/random-pick-index/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
```python
18+
class Solution:
19+
20+
def __init__(self, nums: List[int]):
21+
self.nums = collections.defaultdict(list)
22+
for i, num in enumerate(nums):
23+
self.nums[num].append(i)
24+
25+
26+
def pick(self, target: int) -> int:
27+
lst = self.nums[target]
28+
res = lst[0]
29+
for i in range(1, len(lst)):
30+
n = random.random()
31+
if n < 1 / (1 + i):
32+
res = lst[i]
33+
return res
34+
35+
36+
# Your Solution object will be instantiated and called as such:
37+
# obj = Solution(nums)
38+
# param_1 = obj.pick(target)
39+
```

0 commit comments

Comments
 (0)