Skip to content

Commit ea285c5

Browse files
Linked List Random Node
1 parent 823401c commit ea285c5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Random;
6+
7+
import classes.ListNode;
8+
9+
/**382. Linked List Random Node QuestionEditorial Solution My Submissions
10+
Total Accepted: 43
11+
Total Submissions: 147
12+
Difficulty: Medium
13+
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
14+
15+
Follow up:
16+
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
17+
18+
Example:
19+
20+
// Init a singly linked list [1,2,3].
21+
ListNode head = new ListNode(1);
22+
head.next = new ListNode(2);
23+
head.next.next = new ListNode(3);
24+
Solution solution = new Solution(head);
25+
26+
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
27+
solution.getRandom();
28+
*/
29+
public class LinkedListRandomNode {
30+
31+
}
32+
33+
class Solution {
34+
private Map<Integer, ListNode> map;
35+
private Random rand;
36+
37+
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
38+
public Solution(ListNode head) {
39+
map = new HashMap();
40+
rand = new Random();
41+
int i = 0;
42+
while(head != null){
43+
map.put(i++, head);
44+
head = head.next;
45+
}
46+
}
47+
48+
/** Returns a random node's value. */
49+
public int getRandom() {
50+
return map.get(rand.nextInt(map.size())).val;
51+
}
52+
}
53+

0 commit comments

Comments
 (0)