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

    }
};
相关推荐
czlczl200209259 小时前
算法:组合问题
算法·leetcode·职场和发展
CoderYanger9 小时前
优选算法-字符串:63.二进制求和
java·开发语言·算法·leetcode·职场和发展·1024程序员节
Cx330❀9 小时前
C++ STL set 完全指南:从基础用法到实战技巧
开发语言·数据结构·c++·算法·leetcode·面试
2501_9418053112 小时前
智慧零售平台中的多语言语法引擎与实时推荐系统实践
leetcode
CoderYanger18 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
夏鹏今天学习了吗19 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
墨染点香20 小时前
LeetCode 刷题【172. 阶乘后的零】
算法·leetcode·职场和发展
做怪小疯子20 小时前
LeetCode 热题 100——链表——反转链表
算法·leetcode·链表
做怪小疯子1 天前
LeetCode 热题 100——矩阵——旋转图像
算法·leetcode·矩阵
sin_hielo1 天前
leetcode 2435
数据结构·算法·leetcode