【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?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

方法一:用一个vector存储链表的每个元素,然后用random随机生成一个下标。


c++代码(60ms)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    private:
        vector<int> element;

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public:
        Solution(ListNode* head) {
            while(head!=NULL){
                element.push_back(head->val);
                head=head->next;
            }//while
        }
        
        /** Returns a random node's value. */
        int getRandom() {
            int len=element.size();
            return element[rand()%len];
        }
};

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


方法二:有一个小技巧,可在遍历链表后就能马上得出结果。采用覆盖的形式,边遍历边计数已经到了第几个元素了,比如你在访问第2个元素时,count用来计数,此时count=2,如果rand()%count == 0,那么就存储当前节点的值到result中,那么命中的概率是多少呢,很显然rand()%count只能取0和1,所以概率是1/2,遍历还在继续。然后遍历第3个节点,如果第3个节点命中那么会把第3个节点的值存储到result中从而覆盖掉第2个节点的值。所以对于第2个节点,要想遍历完都不被覆盖(即选中了第2个节点)的概率这样算:1/2 * 2/3 * 3/4 * .... * (n-1)/n = 1/n。同理对于第x个节点,最后命中这个节点的概率这样算:(x-1)/x * x/(x+1) * (x+1)/(x+2) * (n-1)/n = 1/n 。所以所有的节点命中的概率都是1/n了。


c++代码(64ms)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    private:
        ListNode* root;

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public:
        Solution(ListNode* head) {
            root=head;
        }
        
        /** Returns a random node's value. */
        int getRandom() {
            int result=0;
            ListNode *tmp=root;
            for(int count=1;tmp!=NULL;count++,tmp=tmp->next){
                if(rand()%count==0)
                    result=tmp->val;
            }//for
            return result;
        }
};

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值