当前位置:网站首页>2022.07.13_Daily Question
2022.07.13_Daily Question
2022-07-31 07:40:00 【No. い】
382. 链表随机节点
题目描述
给你一个单链表,随机选择链表的一个节点,并返回相应的节点值.每个节点 被选中的概率一样 .
实现 Solution
类:
Solution(ListNode head)
使用整数数组初始化对象.int getRandom()
从链表中随机选择一个节点并返回该节点的值.链表中所有节点被选中的概率相等.
示例:

输入
[“Solution”, “getRandom”, “getRandom”, “getRandom”, “getRandom”, “getRandom”]
[[[1, 2, 3]], [], [], [], [], []]
输出
[null, 1, 3, 2, 2, 3]
解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等.
提示:
- 链表中的节点数在范围
[1, 104]
内 -104 <= Node.val <= 104
- 至多调用
getRandom
方法104
次
进阶:
- 如果链表非常大且长度未知,该怎么处理?
- 你能否在不使用额外空间的情况下解决此问题?
- 水塘抽样
- 链表
- 数学
- 随机化
coding
class Solution1 {
ListNode head;
int size;
public Solution(ListNode head) {
this.head = head;
ListNode cur = head;
while (cur != null) {
cur = cur.next;
size ++;
}
}
public int getRandom() {
int randomNum = (int) (Math.random() * size);
int cnt = 0;
ListNode cur = head;
while (cur != null) {
if (cnt == randomNum) {
return cur.val;
}
cur = cur.next;
cnt ++;
}
return 0;
}
}
// ---------------------------------------------------------------
class Solution2 {
List<Integer> list;
public Solution(ListNode head) {
list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
}
public int getRandom() {
return list.get((int) (Math.random() * list.size()));
}
}
边栏推荐
- 2022.07.15_每日一题
- bcos简介及自序
- Bulk free text translation
- leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
- Log4net 思维导图
- 第9章 异常try...except...else...finally
- How to choose a suitable UI component library in uni-app
- 360 push-360 push tool-360 batch push tool
- 科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
- DirectExchange switch simple introduction demo
猜你喜欢
随机推荐
【面试:并发篇37:多线程:线程池】自定义线程池
事务的传播机制
2022.07.13_每日一题
bcos简介及自序
Obtaining server and client information
Bulk free text translation
LeetCode刷题——摆动序列#376#Medium
剑指offer(一)
DAY18:Xss 靶场通关手册
QFileInfo常规方法
PCB抄板
Gradle剔除依赖演示
SQL Server Datetime2数据类型
【微服务】Nacos集群搭建以及加载文件配置
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
Database Principles Homework 3 — JMU
2022.07.15_每日一题
【解决】mysql本地计算机上的MySQL服务启动后停止。某些服务在未由其他服务或程序使用时将自动停止
强化学习科研知识必备(数据库、期刊、会议、牛人)
Jobject 使用