forked from jeantimex/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked-list-random-node.js
65 lines (59 loc) · 1.51 KB
/
linked-list-random-node.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* Linked List Random Node
*
* 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.
*
* Follow up:
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
*
* Example:
*
* // Init a singly linked list [1,2,3].
* ListNode head = new ListNode(1);
* head.next = new ListNode(2);
* head.next.next = new ListNode(3);
* Solution solution = new Solution(head);
*
* // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
* solution.getRandom();
*
* Your Solution object will be instantiated and called as such:
* var obj = Object.create(Solution).createNew(head)
* var param_1 = obj.getRandom()
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
class Solution {
/**
* @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node.
* @param {ListNode} head
*/
constructor(head) {
this.head = head;
}
/**
* Returns a random node's value.
* @return {number}
*/
getRandom() {
let res = null;
let count = 0;
let node = this.head;
while (node) {
count++;
if (random(0, count) === count - 1) {
res = node.val;
}
node = node.next;
}
return res;
}
}
export { Solution };