Skip to content

Commit 51ce9d6

Browse files
committed
Add solution #382
1 parent 4c28f35 commit 51ce9d6

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,7 @@
300300
378|[Kth Smallest Element in a Sorted Matrix](./0378-kth-smallest-element-in-a-sorted-matrix.js)|Medium|
301301
380|[Insert Delete GetRandom O(1)](./0380-insert-delete-getrandom-o1.js)|Medium|
302302
381|[Insert Delete GetRandom O(1) - Duplicates allowed](./0381-insert-delete-getrandom-o1-duplicates-allowed.js)|Hard|
303+
382|[Linked List Random Node](./0382-linked-list-random-node.js)|Medium|
303304
383|[Ransom Note](./0383-ransom-note.js)|Easy|
304305
384|[Shuffle an Array](./0384-shuffle-an-array.js)|Medium|
305306
387|[First Unique Character in a String](./0387-first-unique-character-in-a-string.js)|Easy|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 382. Linked List Random Node
3+
* https://leetcode.com/problems/linked-list-random-node/
4+
* Difficulty: Medium
5+
*
6+
* Given a singly linked list, return a random node's value from the linked list. Each node must
7+
* have the same probability of being chosen.
8+
*
9+
* Implement the Solution class:
10+
* - Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
11+
* - int getRandom() Chooses a node randomly from the list and returns its value. All the nodes
12+
* of the list should be equally likely to be chosen.
13+
*/
14+
15+
/**
16+
* Definition for singly-linked list.
17+
* function ListNode(val, next) {
18+
* this.val = (val===undefined ? 0 : val)
19+
* this.next = (next===undefined ? null : next)
20+
* }
21+
*/
22+
/**
23+
* @param {ListNode} head
24+
*/
25+
var Solution = function(head) {
26+
this.head = head;
27+
};
28+
29+
/**
30+
* @return {number}
31+
*/
32+
Solution.prototype.getRandom = function() {
33+
let current = this.head;
34+
let result = current.val;
35+
let count = 1;
36+
37+
while (current.next) {
38+
current = current.next;
39+
count++;
40+
if (Math.random() < 1 / count) {
41+
result = current.val;
42+
}
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
 (0)