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

    }
};
相关推荐
hh随便起个名1 小时前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
LYFlied3 小时前
【每日算法】LeetCode 17. 电话号码的字母组合
前端·算法·leetcode·面试·职场和发展
一起养小猫6 小时前
LeetCode100天Day1-字符串匹配与Z字形变换
java·leetcode
yaoh.wang6 小时前
力扣(LeetCode) 1: 两数之和 - 解法思路
python·程序人生·算法·leetcode·面试·跳槽·哈希算法
Code Slacker6 小时前
LeetCode Hot100 —— 滑动窗口(面试纯背版)(四)
数据结构·c++·算法·leetcode
yaoh.wang7 小时前
力扣(LeetCode) 27: 移除元素 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
F_D_Z7 小时前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
flashlight_hi9 小时前
LeetCode 分类刷题:199. 二叉树的右视图
javascript·算法·leetcode
LYFlied9 小时前
【每日算法】LeetCode 46. 全排列
前端·算法·leetcode·面试·职场和发展
LYFlied10 小时前
【每日算法】131. 分割回文串
前端·数据结构·算法·leetcode·面试·职场和发展