leetcode 382. 链表随机节点

从头开始计数
第i个点选择的概率是 1 i \frac{1}{i}

只需要区[0,i-1]的随机数,如果,取到了0,就更新返回值,否则不更新

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. */
    ListNode* head;

    Solution(ListNode* head) {
        this->head = head;
        srand( time(0) );
    }

    /** Returns a random node's value. */
    int getRandom() {
        int cnt = 0;
        int ret = -1;

        ListNode* t = head;
        while( t!=nullptr ){
            cnt ++ ;
            if( rand()%cnt==0 ){
                ret = t->val;
            }
            t = t->next;
        }
        return ret;
    }
};

在这里插入图片描述

发布了286 篇原创文章 · 获赞 57 · 访问量 324万+

猜你喜欢

转载自blog.csdn.net/L1558198727/article/details/104084334