Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up[LeetCode] 382. Linked List Random Node #382
Open
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
这道题给了我们一个链表,让随机返回一个节点,那么最直接的方法就是先统计出链表的长度,然后根据长度随机生成一个位置,然后从开头遍历到这个位置即可,参见代码如下:
解法一:
Follow up 中说链表可能很长,我们没法提前知道长度,这里用到了著名了 水塘抽样 Reservoir Sampling 的思路,由于限定了 head 一定存在,所以先让返回值 res 等于 head 的节点值,然后让 cur 指向 head 的下一个节点,定义一个变量i,初始化为2,若 cur 不为空则开始循环,在 [0, i - 1] 中取一个随机数,如果取出来0,则更新 res 为当前的 cur 的节点值,然后此时i自增一,cur 指向其下一个位置,这里其实相当于维护了一个大小为1的水塘,然后随机数生成为0的话,交换水塘中的值和当前遍历到的值,这样可以保证每个数字的概率相等,参见代码如下:
解法二:
Github 同步地址:
#382
类似题目:
Random Pick Index
参考资料:
https://leetcode.com/problems/linked-list-random-node/
https://leetcode.com/problems/linked-list-random-node/discuss/85662/Java-Solution-with-cases-explain
https://leetcode.com/problems/linked-list-random-node/discuss/85659/Brief-explanation-for-Reservoir-Sampling
https://leetcode.com/problems/linked-list-random-node/discuss/85701/O(n)-Time-and-O(1)-Space-Java-Solution
https://leetcode.com/problems/linked-list-random-node/discuss/85690/using-reservoir-sampling-o1-space-on-time-complexityuff0cc
LeetCode All in One 题目讲解汇总(持续更新中...)