一篇涉及了很多知識的題解
阿新 • • 發佈:2021-09-07
leetcode528 按權重隨機選擇
涵蓋多個c++知識點的題解
class Solution { private: mt19937 gen; uniform_int_distribution<int> dis; vector<int> pre; public: Solution(vector<int>& w): gen(random_device{}()), dis(1, accumulate(w.begin(), w.end(), 0)) { partial_sum(w.begin(), w.end(), back_inserter(pre)); } int pickIndex() { int x = dis(gen); return lower_bound(pre.begin(), pre.end(), x) - pre.begin(); } };
C++STL說明:
- mt19937標頭檔案是
是偽隨機數產生器,用於產生高效能的隨機數 - uniform_int_distribution 標頭檔案在
中,是一個隨機數分佈類,引數為生成隨機數的型別,建構函式接受兩個值表示區間段 - accumulate 標頭檔案在
中,求特定範圍內所有元素的和。 - spartial_sum函式的標頭檔案在
,對(first, last)內的元素逐個求累計和,放在result容器內 - back_inserter函式標頭檔案
,用於在末尾插入元素。 - lower_bound標頭檔案在
,用於找出範圍內不大於num的第一個元素