LeetCode 题解工作台

链表随机节点

给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。 实现 Solution 类: Solution(ListNode head) 使用整数数组初始化对象。 int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

class Solution: def __init__(self, head: Optional[ListNode]):

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样

实现 Solution 类:

  • Solution(ListNode head) 使用整数数组初始化对象。
  • int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。

 

示例:

输入
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
输出
[null, 1, 3, 2, 2, 3]

解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等。

 

提示:

  • 链表中的节点数在范围 [1, 104]
  • -104 <= Node.val <= 104
  • 至多调用 getRandom 方法 104

 

进阶:

  • 如果链表非常大且长度未知,该怎么处理?
  • 你能否在不使用额外空间的情况下解决此问题?
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def __init__(self, head: Optional[ListNode]):
        self.head = head

    def getRandom(self) -> int:
        n = ans = 0
        head = self.head
        while head:
            n += 1
            x = random.randint(1, n)
            if n == x:
                ans = head.val
            head = head.next
        return ans


# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()
speed

复杂度分析

指标
时间complexity is O(N) for initial traversal or O(1) per getRandom call with reservoir sampling if counting is done incrementally. Space complexity is O(1) if only pointers and counters are stored, avoiding extra arrays.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if you can implement getRandom without storing all node values in an array.

  • question_mark

    Expect discussion on uniform probability correctness with repeated calls.

  • question_mark

    Look for use of reservoir sampling or careful pointer updates instead of naïve selection.

warning

常见陷阱

外企场景
  • error

    Replacing selected value incorrectly with wrong probability, causing biased selection.

  • error

    Assuming linked list length is known without counting, leading to index errors.

  • error

    Using extra space unnecessarily instead of O(1) pointer-based methods.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return k random nodes from a linked list with uniform probability.

  • arrow_right_alt

    Support modifications to the linked list between getRandom calls while maintaining uniform selection.

  • arrow_right_alt

    Implement a weighted random selection where nodes have different probabilities based on their values.

help

常见问题

外企场景

链表随机节点题解:链表指针操作 | LeetCode #382 中等