1. 程式人生 > >LeetCode382. 連結串列隨機節點————蓄水池抽樣演算法

LeetCode382. 連結串列隨機節點————蓄水池抽樣演算法

//蓄水池抽樣
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;
	}
};