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

    }
};
相关推荐
武乐乐~3 小时前
欢乐力扣:赎金信
算法·leetcode·职场和发展
sjsjs116 小时前
【数据结构-并查集】力扣1202. 交换字符串中的元素
数据结构·leetcode·并查集
Onlooker1296 小时前
LC-单词搜索、分割回文串、N皇后、搜索插入位置、搜索二维矩阵
算法·leetcode
且听风吟ayan9 小时前
leetcode day19 844+977
leetcode·c#
MiyamiKK579 小时前
leetcode_位运算 190.颠倒二进制位
python·算法·leetcode
C137的本贾尼9 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#
Joyner201810 小时前
python-leetcode-找到字符串中所有字母异位词
算法·leetcode·职场和发展
ll77881110 小时前
LeetCode每日精进:225.用队列实现栈
c语言·开发语言·数据结构·算法·leetcode·职场和发展
不想编程小谭14 小时前
力扣LeetCode: 931 下降路径最小和
数据结构·c++·算法·leetcode·动态规划
Helene190014 小时前
Leetcode 224-基本计算器
算法·leetcode·职场和发展