链表随机节点

题目链接

 解法一:

链表转数组,直接调用随机函数返回即可

class Solution {
    vector<int> vt;
public:
    Solution(ListNode *head) {
        while (head) {
            vt.push_back(head->val);
            head = head->next;
        }
    }
    int getRandom() {
        return vt[rand() % vt.size()];
    }
};

解法二:

水塘抽样法

基本的应用:证明点击跳转我的另一篇博客

class Solution {
public:
    ListNode* root;
    Solution(ListNode* head) {
        root=head;
    }
    
    int getRandom() {
        int ans = root->val;
        int id = 1;
        auto t = root;
        while(t!=NULL){
            if(rand()%id==0){
                ans=t->val;
            }
            id++;
            t=t->next;
        }
        return ans;
    }
};

 

posted @ 2022-01-16 14:18  夜灯长明  阅读(25)  评论(0编辑  收藏  举报