We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent fd95958 commit f0d05eeCopy full SHA for f0d05ee
C++/linked-list-random-node.cpp
@@ -0,0 +1,32 @@
1
+// Time: O(n)
2
+// Space: O(1)
3
+
4
+class Solution {
5
+public:
6
+ /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
7
+ Solution(ListNode* head) : head_(head) {
8
9
+ }
10
11
+ /** Returns a random node's value. */
12
+ int getRandom() {
13
+ auto reservoir = head_->val;
14
+ auto n = 1;
15
+ for (auto curr = head_->next; curr; curr = curr->next) {
16
+ if (rand() % ++n == 0) {
17
+ reservoir = curr->val;
18
19
20
+ return reservoir;
21
22
23
+private:
24
+ ListNode *head_;
25
+};
26
27
+/**
28
+ * Your Solution object will be instantiated and called as such:
29
+ * Solution obj = new Solution(head);
30
+ * int param_1 = obj.getRandom();
31
+ */
32
0 commit comments