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();
*/

最新文章

  1. win7 cmd 操作mysql数据库
  2. asp.net忘记密码功能
  3. EasyUI datagrid优化
  4. Python: PDB命令
  5. python——使用readline库实现tab自动补全
  6. 离线安装chrome插件
  7. IOS开发-表视图LV3导航控制器
  8. 【UVA】11137-Ingenuous Cubrency
  9. C# 关于委托的小例子
  10. MongoDB基础教程系列--第三篇 MongoDB基本操作(二)
  11. 基于Excel参数化你的Selenium2测试代码
  12. Java 高级特性: Lambda 表达式
  13. 51 nod 1766 树上的最远点对(线段树+lca)
  14. GDOI2019游记
  15. [综述]Deep Compression/Acceleration深度压缩/加速/量化
  16. 你好!酷痞Coolpy 之 Linux篇
  17. java 之 异常处理小结
  18. jQuery查找标签--选择器,筛选器,模态对话框, 左侧菜单栏
  19. 阿里云 CentOS 镜像和 EPEL 源
  20. Docker安装(yum方式 centos7)

热门文章

  1. poj2387 Til the Cows Come Home(Dijkstra)
  2. Two-stage rotation animation is deprecated. This application should use the smoother single-stage an
  3. win10 远程桌面远程电脑时每次要输入密码及身份验证错误,要求的函数不受支持问题解决
  4. 【知了堂学习笔记】java 编写几种常见排序算法3
  5. CSUOJ 1021 组合数末尾的零 二进制
  6. Java反射在Android中的使用
  7. 1005 Spell It Right (20)(20 point(s))
  8. nyoj zb的生日
  9. Centos7(Firewall)防火墙开启常见端口命令
  10. hdu 4858 水题