思路:
蓄水池采样。
实现:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 int len=0; 14 ListNode*h=NULL; 15 Solution(ListNode* head) { 16 h=head; 17 while(head){ 18 len++; 19 head=head->next; 20 } 21 } 22 23 int getRandom() { 24 int cur=0; 25 ListNode*tmp=h; 26 for(int i=1;i<=len;i++){ 27 int num=rand()%i; 28 if(num==0)cur=tmp->val; 29 tmp=tmp->next; 30 } 31 return cur; 32 } 33 }; 34 35 /** 36 * Your Solution object will be instantiated and called as such: 37 * Solution* obj = new Solution(head); 38 * int param_1 = obj->getRandom(); 39 */