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

    }
};
相关推荐
im_AMBER26 分钟前
Leetcode 41
笔记·学习·算法·leetcode
Excuse_lighttime2 小时前
排序数组(快速排序算法)
java·数据结构·算法·leetcode·eclipse·排序算法
前进的李工3 小时前
LeetCode hot100:560 和为k的子数组:快速统计法
python·算法·leetcode·前缀和·哈希表
在等晚安么4 小时前
力扣面试经典150题打卡
java·数据结构·算法·leetcode·面试·贪心算法
py有趣5 小时前
LeetCode算法学习之移动0
学习·算法·leetcode
熬了夜的程序员5 小时前
【LeetCode】90. 子集 II
数据结构·算法·leetcode·链表·职场和发展·排序算法
Espresso Macchiato5 小时前
Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array
leetcode·leetcode hard·容斥原理·leetcode 3729·leetcode周赛473·前序和数组
熬了夜的程序员5 小时前
【LeetCode】91. 解码方法
算法·leetcode·链表·职场和发展·排序算法
夏鹏今天学习了吗7 小时前
【LeetCode热题100(54/100)】全排列
算法·leetcode·深度优先
DARLING Zero two♡12 小时前
【优选算法】D&C-Mergesort-Harmonies:分治-归并的算法之谐
java·数据结构·c++·算法·leetcode