每日一题 382. 链表随机节点

382. 链表随机节点

简单

cpp 复制代码
class Solution {
public:
    int  n;
    ListNode* head;
    Solution(ListNode* head) {
        int cnt = 0;
        this->head = head;
        while(head != 0)
        {
            head = head->next;
            ++cnt;
        }
        n =  cnt;
    }
    
    int getRandom() {
        int idx = rand() % n;
        ListNode* h = head;
        while(idx != 0)
        {
            h = h->next;
            idx--;
        }
        return h->val;

    }
};
相关推荐
晚笙coding1 小时前
LeetCode 98:验证二叉搜索树 —— 从局部判断到全局范围约束的递归思想
算法·leetcode·职场和发展
兰令水2 小时前
hot100【acm版】【2026.7.21打卡-java版本】
java·开发语言·算法·leetcode·面试
退休倒计时3 小时前
【每日一题】LeetCode 131. 分割回文串 TypeScript
算法·leetcode·typescript
旖-旎20 小时前
LeetCode 279:完全平方数(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
良木林1 天前
滑动窗口 - LeetCode hot 100
javascript·算法·leetcode·双指针·滑动窗口
晚笙coding1 天前
LeetCode 108:将有序数组转换为二叉搜索树 —— 从数组到平衡二叉树的递归构造
数据结构·算法·leetcode
hold?fish:palm1 天前
7 接雨水
开发语言·c++·leetcode
tkevinjd1 天前
力扣148-排序链表
算法·leetcode·链表
wabs6662 天前
关于图论【力扣797.所有可能的路径的思考】
算法·leetcode·图论
Navigator_Z2 天前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode