给一个单向链表,随机选择一个node in one pass
来源:互联网 发布:电脑ps软件 编辑:程序博客网 时间:2024/04/28 00:04
public class ReserviorSampling { public ListNode sampling(ListNode head){ ListNode s = head; Random rand = new Random(); int count = 1; while(head != null){ int position = (int) (rand.nextInt(count) + 1); count++; if(position == 1) s = head; } return s; }}
这个题可以有变种。
当要随机选择k个时。
public class ReserviorSampling { public ListNode sampling(ListNode head){ Queue<ListNode> q = new Queue<ListNode>; Random rand = new Random(); int count = 1; while(head != null){ int position = (int) (rand.nextInt(count) + 1); count++; if(position <= k) {if(q.size() == k)q.pop(); q.push(head);} } return s; }}
- 给一个单向链表,随机选择一个node in one pass
- 随机选择一个文件
- 反转一个单向链表
- 建立一个单向链表
- 给一个node添加监听
- 25. Reverse Nodes in k-Group 怎样不使用额外空间翻转一个单向链表?
- 将一个单向链表反向链接
- 一个简单的"单向链表"
- 单向链表的一个面试题
- 一个复杂一点的单向链表
- 将一个单向链表逆序
- 第五章 一个单向链表实例
- 一个简单的单向链表
- 将一个单向链表逆序
- 对一个单向链表进行逆序
- Plus One 给一个数加上1
- Print assembler hex in one pass
- 给一个生成随机码的函数
- 【黑马程序员】面向对象(一) 第五天
- 朋友早早就拟好了路线700
- C++学习笔记5——语句
- [Leetcode] Remove Nth Node From End of List
- 二叉树inorder iterator的跌代器
- 给一个单向链表,随机选择一个node in one pass
- 关于运算符重载(总结)
- VS2010使用MFC类向导时提示“灾难性故障”的解决 .
- linux学习入门3——linux文件基本操作(linuxcast.net)(复制、移动、重命名、创建、删除文件及文件夹)
- Ajax实现异步请求的整个过程
- 把一个长度为n的数组分成k段,让每段和的最大值最小。
- addEventListener和attachEvent以及事件句柄绑定的区别
- 使用SQL Server维护计划实现数据库定时自动备份
- mfc基本对话框中的控件透明到背景图片