From 620ec5d91172307aed652e7e8f3a422754809ee2 Mon Sep 17 00:00:00 2001 From: Dipendra Raghav <90553063+Dipendra-Raghav@users.noreply.github.com> Date: Sat, 11 Mar 2023 01:01:03 +0530 Subject: [PATCH] Time: 28 ms (33.38%), Space: 16.7 MB (57.94%) - LeetHub --- .../0382-linked-list-random-node.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 0382-linked-list-random-node/0382-linked-list-random-node.cpp diff --git a/0382-linked-list-random-node/0382-linked-list-random-node.cpp b/0382-linked-list-random-node/0382-linked-list-random-node.cpp new file mode 100644 index 0000000..8ee0c88 --- /dev/null +++ b/0382-linked-list-random-node/0382-linked-list-random-node.cpp @@ -0,0 +1,28 @@ +class Solution +{ + vector v; + int n; + +public: + Solution(ListNode *head) + { + ListNode *ptr = head; + while (ptr) + { + v.push_back(ptr->val); + ptr = ptr->next; + } + n = v.size(); + } + + int getRandom() + { + static int i = 0; + if (i == 0) + { + srand(time(NULL)); + i++; + } + return v[rand() % n]; + } +}; \ No newline at end of file