每日一题 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;

    }
};
相关推荐
alphaTao13 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
CoderYanger1 天前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
Navigator_Z1 天前
LeetCode //C - 1221. Split a String in Balanced Strings
c语言·算法·leetcode
玄昌盛不会编程1 天前
LeetCode——2091. 从数组中移除最大值和最小值
java·算法·leetcode
旖旎夜光1 天前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
学习星球2 天前
单调栈——从“找下一个更大的“到柱状图中的最大矩形
数据库·c++·算法·leetcode·xcode
血小板要健康2 天前
网格 dfs 与 FloodFill:从岛屿、区域到搜索路径
笔记·算法·leetcode·深度优先
鹿角片ljp2 天前
LeetCode 141. 环形链表|从 HashSet 到快慢指针 O (1) 空间最优解
算法·leetcode·链表
ZC跨境爬虫2 天前
LeetCode 219. 存在重复元素 II(滑动窗口 + 哈希表详解)
算法·leetcode·散列表
Navigator_Z2 天前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode