LeetCode 382. Linked List Random Node 题解(C++)
题目描述
- 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.
示例
// 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();
补充
- What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
思路
我的思路
- 在构造函数里用一个while循环计算出链表的长度length,然后用随机函数rand()对length取余,得到随机的链表位置pos,之后再对链表做一次遍历,到达链表的pos位置(这里假设链表的位置从0开始),取出该位置链表结点的值返回即可。
其它解法
这种解法使用了蓄水池抽样算法。蓄水池抽样算法简单叙述如下:
假设我们要从n个数中取出k个数,且保证每个数被取出的概率为k/n,我们可以用O(n)的时间复杂度去完成,这里就需要用到蓄水池抽样算法。算法的步骤为:
1.将n个数中的前k个数放置到k长度的数组(即蓄水池)中;
2.对于第k+1个数,有k/k+1的概率选中它并随机替换掉蓄水池中的一个数;
3.对于第k+i个数,有k/k+i的概率选中它并随机替换掉蓄水池中的一个数;
4.一直循环2,3步骤直到k+i=n。
该算法的证明这里暂且不详述,有兴趣的可以查阅相关资料。在本题中,上述的k值为1,我们首先将链表头结点的值放到蓄水池(本题我们的水池只有一个数),之后从第二个结点开始循环上述的2,3步骤,这里第i个结点被放到蓄水池的概率为1/i,我们使rand()%i是否等于0来判断该结点的值是否应该放到蓄水池中,因为rand()%i等于0的概率就是为1/i;
- 循环上面的步骤直到指针指向空节点即可。
代码
我的代码
/**
* 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;
length = 0;
ListNode *temp = this->head;
while (temp != NULL)
{
++length;
temp = temp->next;
}
}
/** Returns a random node's value. */
int getRandom()
{
ListNode *temp = head;
int result = 0;
int pos = rand() % length;
for (int i = 0; i < length; ++i)
{
if (i == pos)
{
result = temp->val;
break;
}
temp = temp->next;
}
return result;
}
private:
ListNode *head;
int length;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
另一种解法的代码
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;
}
/** Returns a random node's value. */
int getRandom()
{
int result = head->val;
ListNode *temp = head->next;
int i = 2;
while (temp)
{
int j = rand() % i;
if (j == 0)
{
result = temp->val;
}
++i;
temp = temp->next;
}
return result;
}
private:
ListNode *head;
};