题目来源
题目描述
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
Solution(ListNode *head){
}
int getRandom(){
}
};
题目解析
链表转数组
class Solution {
std::vector<int> vec;
public:
Solution(ListNode* head) {
while (head){
vec.emplace_back(head->val);
head = head->next;
}
}
int getRandom() {
std::random_device rd; //如果可用的话,从一个随机数发生器上获得一个真正的随机数
std::mt19937 gen(rd()); //gen是一个使用rd()作种子初始化的标准梅森旋转算法的随机数发生器
std::uniform_int_distribution<> distrib(0, vec.size() - 1);
return vec[ distrib(gen) ];
}
};
蓄水池抽样算法
可以用于大数据流中的随机抽样问题。
即:当内存无法加载全部数据时,如果从包含未知大小的数据流中随机选取k个数据,并且要求保证每个数据倍抽取到的概率相等。
class Solution {
public:
Solution(ListNode *head){
this->head = head;
}
int getRandom(){
int res = head->val, i = 2;
ListNode *cur = head->next;
while (cur){
int j = rand() % i;
if(j == 0){
res = cur->val;
}
++i;
cur = cur->next;
}
return res;
}
private:
ListNode *head;
};