forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_382.java
36 lines (29 loc) · 880 Bytes
/
_382.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
30
31
32
33
34
35
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class _382 {
public static class Solution {
private Map<Integer, ListNode> map;
private Random rand;
/**
* @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node.
*/
public Solution(ListNode head) {
map = new HashMap();
rand = new Random();
int i = 0;
while (head != null) {
map.put(i++, head);
head = head.next;
}
}
/**
* Returns a random node's value.
*/
public int getRandom() {
return map.get(rand.nextInt(map.size())).val;
}
}
}