382. Linked List Random Node

Posted bright-mark

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了382. Linked List Random Node相关的知识,希望对你有一定的参考价值。

蓄水池原理

/**
 * 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的主要内容,如果未能解决你的问题,请参考以下文章

382. Linked List Random Node

382. Linked List Random Node

382. Linked List Random Node 链接列表随机节点

Reservoir Sampling-382. Linked List Random Node

[leetcode]Reservoir Sampling-382. Linked List Random Node

[LeetCode] 382. Linked List Random Node 链表随机节点