LeetCode 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:
1
2
3
4
5
6
7
8 // 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();
要求设计一个类, 根据一个未知长度的单链表进行构造, 每次调用getRandom
成员函数时返回一个随机节点.
O(n)空间复杂度, O(1)时间复杂度的方法就是用一个顺序容器保存所有节点的指针, 然后每次调用getRandom
都根据下标来访问.
1 | class Solution { |
对于题目中的Follow up部分, 要使用O(1)空间复杂度, O(n)时间复杂度. 在类中只保存链表头结点和当前访问节点, 每次生成的随机数是下一个节点与当前节点的距离.
1 | class Solution { |