【leetcode】382. Linked List Random Node

题目:
Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?


思路:
抄作业https://www.cnblogs.com/grandyang/p/5759926.html,引用其关键部分:

这里用到了著名了 水塘抽样 Reservoir Sampling 的思路,由于限定了 head 一定存在,所以先让返回值 res 等于 head 的节点值,然后让 cur 指向 head 的下一个节点,定义一个变量i,初始化为2,若 cur 不为空则开始循环,在 [0, i - 1] 中取一个随机数,如果取出来0,则更新 res 为当前的 cur 的节点值,然后此时i自增一,cur 指向其下一个位置,这里其实相当于维护了一个大小为1的水塘,然后随机数生成为0的话,交换水塘中的值和当前遍历到的值,这样可以保证每个数字的概率相等。


代码实现:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
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) {
        this->head = head;
    }
    
    /** Returns a random node's value. */
    int getRandom() {
        int res = head->val;
        int i = 2;
        ListNode *cur = head->next;
        
        while (cur){ // 把除head外的所有node都遍历一遍
            int t = rand() % i; // 在 [0,i-1] 中随即抽一个数
            if (t == 0){ // 如果抽的数是0,则更新res
                res = cur->val;
            }
            ++i;
            cur = cur->next;
        }
        
        return res;
    }
private:
    ListNode *head;
};

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

参考:
https://www.cnblogs.com/grandyang/p/5759926.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值