链表随机节点
解法一:
链表转数组,直接调用随机函数返回即可
class Solution { vector<int> vt; public: Solution(ListNode *head) { while (head) { vt.push_back(head->val); head = head->next; } } int getRandom() { return vt[rand() % vt.size()]; } };
解法二:
水塘抽样法
基本的应用:证明点击跳转我的另一篇博客
class Solution { public: ListNode* root; Solution(ListNode* head) { root=head; } int getRandom() { int ans = root->val; int id = 1; auto t = root; while(t!=NULL){ if(rand()%id==0){ ans=t->val; } id++; t=t->next; } return ans; } };