linked-list-random-node
2024-10-06 10:17:17
https://leetcode.com/problems/linked-list-random-node/ // Using Reservoir sampling algorithm
// https://discuss.leetcode.com/topic/53812/using-reservoir-sampling-o-1-space-o-n-time-complexity-c/2 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode h;
java.util.Random rand; /** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
h = head;
rand = new java.util.Random();
} /** Returns a random node's value. */
public int getRandom() {
if (h == null) {
return 0;
} int ret = h.val;
int i = 1;
ListNode cur = h;
while (cur.next != null) {
cur = cur.next;
i++;
int f = rand.nextInt() % i;
if (f == 0) {
ret = cur.val;
}
}
return ret;
}
} /**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
最新文章
- win7 cmd 操作mysql数据库
- asp.net忘记密码功能
- EasyUI datagrid优化
- Python: PDB命令
- python——使用readline库实现tab自动补全
- 离线安装chrome插件
- IOS开发-表视图LV3导航控制器
- 【UVA】11137-Ingenuous Cubrency
- C# 关于委托的小例子
- MongoDB基础教程系列--第三篇 MongoDB基本操作(二)
- 基于Excel参数化你的Selenium2测试代码
- Java 高级特性: Lambda 表达式
- 51 nod 1766 树上的最远点对(线段树+lca)
- GDOI2019游记
- [综述]Deep Compression/Acceleration深度压缩/加速/量化
- 你好!酷痞Coolpy 之 Linux篇
- java 之 异常处理小结
- jQuery查找标签--选择器,筛选器,模态对话框, 左侧菜单栏
- 阿里云 CentOS 镜像和 EPEL 源
- Docker安装(yum方式 centos7)
热门文章
- poj2387 Til the Cows Come Home(Dijkstra)
- Two-stage rotation animation is deprecated. This application should use the smoother single-stage an
- win10 远程桌面远程电脑时每次要输入密码及身份验证错误,要求的函数不受支持问题解决
- 【知了堂学习笔记】java 编写几种常见排序算法3
- CSUOJ 1021 组合数末尾的零 二进制
- Java反射在Android中的使用
- 1005 Spell It Right (20)(20 point(s))
- nyoj zb的生日
- Centos7(Firewall)防火墙开启常见端口命令
- hdu 4858 水题