382. Linked List Random Node 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 1 - cheat , container to store12345678910111213141516class Solution {private: vector<int> vec; int size ;public: Solution(ListNode* head) { size = 0; ListNode *p; for(p=head;p;p=p->next) {vec.push_back(p->val);size++;} } int getRandom() { return vec[rand()%size]; }}; option 2 - algo123456789101112131415161718192021class Solution {private: ListNode* head;public: Solution(ListNode* head) { this->head = head; } int getRandom() { int count = 1; ListNode *p = head; int ret = 0; while(p){ if(rand()%count==0) ret = p->val; count++; p=p->next; } return ret; }};