-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_398.java
29 lines (23 loc) · 821 Bytes
/
_398.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.fishercoder.solutions.firstthousand;
import java.util.*;
public class _398 {
// TODO: use reservoir sampling to solve it again
// reservoir sampling: the size of the dataset is unknow before hand
public static class Solution {
Map<Integer, List<Integer>> map;
Random random;
public Solution(int[] nums) {
map = new HashMap<>();
random = new Random();
for (int i = 0; i < nums.length; i++) {
List<Integer> list = map.getOrDefault(nums[i], new ArrayList<>());
list.add(i);
map.put(nums[i], list);
}
}
public int pick(int target) {
List<Integer> list = map.get(target);
return list.get(random.nextInt(list.size()));
}
}
}