2022-1-16 382 链表随机节点

382 链表随机节点

题目描述

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

实现 Solution 类:

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

示例:

img

输入
["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

进阶:

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

解法一:基本解法

概述

分成两步,分别对应构造函数和另个函数 getRandom()。首先,在构造函数中将给定的链表遍历并且将数据放到动态数组中。然后在另一个函数中,使用Random类获得一个随机数[0,list.size()),返回随机数下标处的值即可。

优点和缺点

优点:写起来比较简单

缺点:当链表非常大的时候,需要在内存中存一个几乎相同大小的动态数组,内存消耗较大。

代码实现

/**
 * 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;
    public Solution(ListNode head) {
        list = new ArrayList<>();
        while(head!=null){
            list.add(head.val);
            head = head.next;
        }
    }

    public int getRandom() {
        return list.get(new Random().nextInt(list.size()));
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

解法二:水塘抽样

概述

该抽样方法用到了数学知识。

过程为,我们遍历整个数组,遍历第i个节点时我们选择这个节点的概率为1/i,选择其他节点的概率为i-1/i,乘到最后发现每一个节点被选择的概率都是1/n

优点

几乎没有空间复杂度,时间复杂度为遍历整个链表的时间复杂度。

代码实现

/**
 * 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 {
    ListNode head;
    Random random;
    public Solution(ListNode head) {
        this.head = head;
        random = new Random();
    }
    public int getRandom() {
        int i = 1;
        int result = 0;
        for(ListNode p = head;p != null;p = p.next){
            if(random.nextInt(i) == 0){
                result = p.val;
            }
            i++;
        }
        return result;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */
posted @ 2022-01-16 11:42  吃心王  阅读(48)  评论(0)    收藏  举报