LeetCode382. 链表随机节点————蓄水池抽样算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Ming991301630/article/details/83152450
//蓄水池抽样
class Solution {
private:
	ListNode * HEAD;
public:
        //初始化
	Solution(ListNode* head) {
		srand((unsigned)time(nullptr));
		HEAD = head;
	}
        //获取链表上的随机节点的值
	int getRandom() {
		ListNode *result = HEAD;//结果选中的节点
		ListNode *cur = HEAD->next;//当前遍历的节点
		int i = 2;
		while (cur!=nullptr)//遍历每一个节点
		{
			if (rand() % i == 0) {//i分之一决定是否将result替换为cur
				result = cur;//替换
			}
			++i;
			cur = cur->next;
		}
		return result->val;
	}
};

猜你喜欢

转载自blog.csdn.net/Ming991301630/article/details/83152450
今日推荐