Linked List Random Node

原创 2016年08月31日 09:42:53

水塘抽样算法:

关键点是不知道样本总大小,抽样要等概率

算法过程:遍历一遍链表,每遍历到一个元素时记当前元素编号为n,生成随机数,若随机数小于1/n,则令该元素作为结果,这样进行下去,遍历到最后得到的结果的被抽取概率就是1/N,也就能保证所有元素都是等概率抽取的。

参考公式为:

                        

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. */
	ListNode* p;
	Solution(ListNode* head) {
		p = head;
	}

	/** Returns a random node's value. */
	int getRandom() {
		int res = p->val;
		ListNode* node = p->next;
		int i = 2;
		while (node) {
			int j = rand() % i;
			if (j == 0)//这样写的原理是:若生成的随机数在0~i之间,则j=0时rand()=i,
                                   //若生成的随机数在0~2i之间时,rand()=i或2i时j=0,以此类推,这样就保证了上面说明中随机数小于1/n那条性质
				res = node->val;
			i++;
			node = node->next;
		}
		return res;
	}
};


相关文章推荐

382. Linked List Random Node(返回链表中随机一个节点的值)

Given a singly linked list, return a random node's value from the linked list. Each node must have t...

LeetCode-难题集之Linked List Random Node

Linked List Random Node:https://leetcode.com/problems/linked-list-random-node/ Linked List Random...
  • ww2041
  • ww2041
  • 2016年08月26日 10:10
  • 169

[leetcode] 382. Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have t...

LeetCode:382 Linked List Random Node

382. Linked List Random Node Given a singly linked list, return a random node’s value from the lin...
  • Wisimer
  • Wisimer
  • 2016年08月11日 09:45
  • 655

Leetcode 382. Linked List Random Node

382. Linked List Random Node Total Accepted: 4707 Total Submissions: 10107 Difficulty: Medium Gi...

[leetcode] 382. Linked List Random Node 解题报告

题目链接: https://leetcode.com/problems/linked-list-random-node/ Given a singly linked list, return a ...

LeetCode[382] Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have t...

[leetcode]-Linked List Random Node

题目描述:给定一个单向的链表,要求以相等的概率返回要求:时间复杂度o(n),空间复杂度o(1)原文描述:Given a singly linked list, return a random node...

[Leetcode]382. Linked List Random Node

题目:[leetcode]Given a singly linked list, return a random node’s value from the linked list. Each nod...

382. Linked List Random Node

原题链接:https://leetcode.com/problems/linked-list-random-node/Given a singly linked list, return a rand...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Linked List Random Node
举报原因:
原因补充:

(最多只允许输入30个字)