|
| 1 | +<h2><a href="https://leetcode.com/problems/linked-list-random-node/">382. Linked List Random Node</a></h2><h3>Medium</h3><hr><div><p>Given a singly linked list, return a random node's value from the linked list. Each node must have the <strong>same probability</strong> of being chosen.</p> |
| 2 | + |
| 3 | +<p>Implement the <code>Solution</code> class:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li><code>Solution(ListNode head)</code> Initializes the object with the integer array nums.</li> |
| 7 | + <li><code>int getRandom()</code> Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be choosen.</li> |
| 8 | +</ul> |
| 9 | + |
| 10 | +<p> </p> |
| 11 | +<p><strong>Example 1:</strong></p> |
| 12 | +<img alt="" src="https://assets.leetcode.com/uploads/2021/03/16/getrand-linked-list.jpg" style="width: 302px; height: 62px;"> |
| 13 | +<pre><strong>Input</strong> |
| 14 | +["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"] |
| 15 | +[[[1, 2, 3]], [], [], [], [], []] |
| 16 | +<strong>Output</strong> |
| 17 | +[null, 1, 3, 2, 2, 3] |
| 18 | + |
| 19 | +<strong>Explanation</strong> |
| 20 | +Solution solution = new Solution([1, 2, 3]); |
| 21 | +solution.getRandom(); // return 1 |
| 22 | +solution.getRandom(); // return 3 |
| 23 | +solution.getRandom(); // return 2 |
| 24 | +solution.getRandom(); // return 2 |
| 25 | +solution.getRandom(); // return 3 |
| 26 | +// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. |
| 27 | +</pre> |
| 28 | + |
| 29 | +<p> </p> |
| 30 | +<p><strong>Constraints:</strong></p> |
| 31 | + |
| 32 | +<ul> |
| 33 | + <li>The number of nodes in the linked list will be in the range <code>[1, 10<sup>4</sup>]</code>.</li> |
| 34 | + <li><code>-10<sup>4</sup> <= Node.val <= 10<sup>4</sup></code></li> |
| 35 | + <li>At most <code>10<sup>4</sup></code> calls will be made to <code>getRandom</code>.</li> |
| 36 | +</ul> |
| 37 | + |
| 38 | +<p> </p> |
| 39 | +<p><strong>Follow up:</strong></p> |
| 40 | + |
| 41 | +<ul> |
| 42 | + <li>What if the linked list is extremely large and its length is unknown to you?</li> |
| 43 | + <li>Could you solve this efficiently without using extra space?</li> |
| 44 | +</ul> |
| 45 | +</div> |
0 commit comments