方法1:数组法——将链表中所有节点的值存进数组,然后使用rand()%len随机选择。
class Solution {
public:
vector<int> res;
Solution(ListNode* head) {
while(head)
{
res.push_back(head->val);
head=head->next;
}
}
int getRandom() {
int len=res.size();
int ans=res[rand()%len];
return ans;
}
};
方法2: 蓄水池算法
class Solution {
public:
ListNode* head;
Solution(ListNode* head) {
this->head=head;
}
int getRandom() {
int i=0;
int ans=0;
for(ListNode* p=head;p;p=p->next)
{
i++;
if(rand()%i==0)
{
ans=p->val;
}
}
return ans;
}
};