-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomSolution.java
More file actions
52 lines (44 loc) · 1.45 KB
/
RandomSolution.java
File metadata and controls
52 lines (44 loc) · 1.45 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Author : WindAsMe
* File : RandomSolution.java
* Time : Create on 18-9-7
* Location : ../Home/JavaForLeeCode2/RandomSolution.java
* Function : LeetCode No.398
*/
public class RandomSolution {
static class Solution {
private Map<Integer, List<Integer>> map;
public Solution(int[] nums) {
this.map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.get(nums[i]) == null) {
List<Integer> list = new ArrayList<>();
list.add(i);
map.put(nums[i], list);
} else {
List<Integer> list = map.get(nums[i]);
list.add(i);
map.put(nums[i], list);
}
}
}
public int pick(int target) {
List<Integer> list = map.get(target);
return list.get((int) (Math.random() * list.size()));
}
public void occur() {
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue().toString());
}
}
}
public static void main(String[] args) {
int[] nums = {1,2,3,3,3};
Solution s = new Solution(nums);
System.out.println(s.pick(3));
}
}