Leetcode—382. 链表随机节点【中等】(水塘抽样法)

2024每日刷题(一零九)

Leetcode—382. 链表随机节点

Leetcode—382. 链表随机节点【中等】(水塘抽样法)_第1张图片

算法思想

我们可以在初始化时,用一个数组记录链表中的所有元素,这样随机选择链表的一个节点,就变成在数组中随机选择一个元素

实现代码

/**
 * 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:
    vector<int> arr;
    Solution(ListNode* head) {
        for(ListNode* cur = head; cur; cur=cur->next) {
            arr.push_back(cur->val);
        }
    }
    
    int getRandom() {
        return arr[rand()%arr.size()];
    }
};

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

运行结果

Leetcode—382. 链表随机节点【中等】(水塘抽样法)_第2张图片

水塘抽样法

Leetcode—382. 链表随机节点【中等】(水塘抽样法)_第3张图片

实现代码

/**
 * 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:
    Solution(ListNode* head): sohead(head) {

    }
    
    int getRandom() {
        int ans = 1e5;
        int i = 1;
        for(ListNode* cur = sohead; cur; cur = cur->next, i++) {
            if(rand()%i==0) {
                ans = cur->val;
            }
        }
        return ans;
    }
private:
    ListNode* sohead;
};

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

运行结果

Leetcode—382. 链表随机节点【中等】(水塘抽样法)_第4张图片

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,链表,算法,c++,数据结构,经验分享)