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

    }
};
相关推荐
飞川撸码2 小时前
【LeetCode 热题100】208:实现 Trie (前缀树)(详细解析)(Go语言版)
算法·leetcode·golang·图搜索算法
Fantasydg6 小时前
DAY 31 leetcode 142--链表.环形链表
算法·leetcode·链表
moz与京6 小时前
[附C++,JS,Python题解] Leetcode 面试150题(10)——轮转数组
c++·python·leetcode
拾零吖9 小时前
枚举算法-day2
数据结构·算法·leetcode
Allen Wurlitzer10 小时前
算法刷题记录——LeetCode篇(8.7) [第761~770题](持续更新)
算法·leetcode·职场和发展
LuckyAnJo13 小时前
Leetcode-100 回溯法-电话号码的字母组合
python·算法·leetcode
LuckyLay14 小时前
LeetCode算法题(Go语言实现)_20
算法·leetcode·职场和发展·golang
AI是这个时代的魔法17 小时前
Using Dyck Path to solve a leetcode puzzle
python·算法·leetcode
moz与京18 小时前
【附JS、Python、C++题解】Leetcode面试150题(12)多数问题
javascript·python·leetcode
pilgrim5318 小时前
【二刷代码随想录】双指针-数组相关题型、推荐习题
java·数据结构·算法·leetcode