码迷,mamicode.com
首页 > 其他好文 > 详细

382. Linked List Random Node

时间:2018-09-07 14:13:12      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:def   you   ext   blank   while   ==   ast   rand   hat   

蓄水池原理

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
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. */
    Solution(ListNode* head) {
        p=head;
    }
    
    /** Returns a random node‘s value. */
    int getRandom() {
        int val=p->val;
        int i=2;
        ListNode* cur=p->next;
        while(cur){
            int j=rand()%i;
            if(j==0) val=cur->val;
            i++;cur=cur->next;
        }
        return val;
    }
private:
    ListNode* p;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

 

382. Linked List Random Node

标签:def   you   ext   blank   while   ==   ast   rand   hat   

原文地址:https://www.cnblogs.com/bright-mark/p/9603861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!