1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_382.java 1.49 KB
一键复制 编辑 原始数据 按行查看 历史
Fisher Coder 提交于 2019-02-16 22:59 +08:00 . refactor 382
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**382. Linked List Random Node
*
Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();
*/
public class _382 {
public static class Solution1 {
private Map<Integer, ListNode> map;
private Random rand;
/**
* @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node.
*/
public Solution1(ListNode head) {
map = new HashMap();
rand = new Random();
int i = 0;
while (head != null) {
map.put(i++, head);
head = head.next;
}
}
/**
* Returns a random node's value.
*/
public int getRandom() {
return map.get(rand.nextInt(map.size())).val;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助