File tree 2 files changed +47
-0
lines changed 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change 300
300
378|[ Kth Smallest Element in a Sorted Matrix] ( ./0378-kth-smallest-element-in-a-sorted-matrix.js ) |Medium|
301
301
380|[ Insert Delete GetRandom O(1)] ( ./0380-insert-delete-getrandom-o1.js ) |Medium|
302
302
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|
303
304
383|[ Ransom Note] ( ./0383-ransom-note.js ) |Easy|
304
305
384|[ Shuffle an Array] ( ./0384-shuffle-an-array.js ) |Medium|
305
306
387|[ First Unique Character in a String] ( ./0387-first-unique-character-in-a-string.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments