题目:
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. solution.getRandom();
思路:
最近的题目感觉和随机数相关的比较多,不过这个确实是面试的趋势。对于本题目,我们首先看看允许使用额外空间的解法,然后再看看如果不允许使用额外空间,怎么利用Reservior Sampling方法获得随机结点,这应该是本题目考查的重点。
1、使用额外空间:我们将单链表的结点值都拷贝到一个数组中,然后产生一个随机数索引,返回随机索引对应的值即可。这种做法的空间复杂度是O(n);构造函数的时间复杂度是O(n),getRandom函数的时间复杂度是O(1)。另外一个变种是我们在构造函数中计算出整个单链表的长度length,然后在getRandom方法中,随机产生一个介于[0, length]之间的数x,然后遍历单链表,返回第x个结点。这种做法的空间复杂度可以降低到O(1),但是getRandom的时间复杂度是O(n)。以上两种做法在length变为无限大的时候都会失效。
2、不使用额外空间:先来介绍一下Reservior Sampling方法,这种采样非常适合于流数据。怎么做呢?假设目前我们已经处理了n个结点,而当前选中的采样点是x(1 <= x <= n);这样当我们遇到第n+1个结点的时候,让x以1 / (n + 1)的概率转移到第n+1个结点。可以用概率论的知识证明当处理完所有结点后,每个结点被采样的概率是相同的。具体实现请见下面的代码。
代码:
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) {
ListNode* node = head;
while(node != NULL) {
vec.push_back(node->val);
node = node->next;
}
}
/** Returns a random node's value. */
int getRandom() {
if(vec.size() == 0) {
return -1;
}
return vec[rand() % vec.size()];
}
private:
vector<int> vec;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
2、不使用额外空间:
/**
* 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) {
random_list = head;
}
/** Returns a random node's value. */
int getRandom() {
ListNode* temp = random_list;
int value = random_list->val;
for (int i = 1; temp != NULL; ++i) {
if (rand() % i == 0) { // the propability is 1 / i
value = temp->val;
}
temp = temp->next;
}
return value;
}
private:
ListNode* random_list;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/