方法一:动态整数数组
Java:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
List<Integer> list;
Random random;
public Solution(ListNode head) {
list = new ArrayList<>();
ListNode cur = head;
random = new Random();
while (cur != null) {
list.add(cur.val);
cur = cur.next;
}
}
public int getRandom() {
return list.get(random.nextInt(list.size()));
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/
复杂度分析
- 时间复杂度:初始化为 O(n),随机选择为 O(1),其中 nn 是链表的元素个数。
- 空间复杂度:O(n)。我们需要 O(n) 的空间存储链表中的所有元素。
方法二:水塘抽样
class Solution {
ListNode head;
Random random;
public Solution(ListNode head) {
this.head = head;
random = new Random();
}
public int getRandom() {
int ans = 0, i = 1;
for (ListNode node = head; node != null; node = node.next) {
if (random.nextInt(i) == 0) {
ans = node.val;
}
i++;
}
return ans;
}
}
复杂度分析
- 时间复杂度:初始化为 O(1),随机选择为 O(n),其中 n 是链表的元素个数。
- 空间复杂度:O(1)。我们只需要常数的空间保存若干变量。
终于放假啦,开始寒假的学习啦!!