首页 > 其他 > 详细

382. Linked List Random Node

时间:2018-09-07 13:11:00      阅读:94      评论:0      收藏:0      [点我收藏+]

蓄水池原理

/**
 * 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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!