1. 解析
题目大意,随机返回链表中1个节点的值
2. 分析
我最初想到的解法就是,遍历整个链表,获取链表的长度length,然后根据生成随机数的库函数rand()获取一个[1, length]范围内的随机数,返回对应编号的链表节点。这种方法可以AC,但存在一个问题,当链表无限大,即我们无法获取链表的长度时,这种方法就行不通啦~~~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
this->root = head;
this->length = 0;
while (head != NULL){ //获取链表的长度
this->length++;
head = head->next;
}
}
/** Returns a random node's value. */
int getRandom() {
int index = rand() % length + 1; //获取[1, length]随机数
ListNode* cur = this->root;
while (--index > 0){
cur = cur->next;
}
return cur->val; //返回指定编号的节点对应的值
}
private:
ListNode* root;
int length;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
3. 水塘抽样解法
最怕的就是涉及定理或者有关数学知识的题,因为你如果没碰到过,是不可能做出来的,学数学的人厉害的地方就在这里,人家是创造者,而我们只是实践者,哎~~~
水塘抽样可以参考Hi,Fairy.的这篇博客,我浏览过很多其他博客,这篇是写的最到位的。
因为这里只要求我们返回一个节点的值,故我们只需维持1个大小的水塘即可,大家去看一下上面那篇博客就理解啦.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
this->head = head;
}
int getRandom() {
int res = -1, i = 1;
ListNode *cur = head;
while (cur) {
int j = rand() % i; //生成[0, i)的随机数
if (j == 0) res = cur->val; //只维持一个大小的水塘
++i;
cur = cur->next;
}
return res;
}
private:
ListNode *head;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/