菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
87
0

0382. Linked List Random Node (M)

原创
05/13 14:22
阅读数 31787

Linked List Random Node (M)

题目

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:

// 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();

题意

思路

最简单的方法是直接遍历链表,把值全部存到List中,最后随机下标即可。

官方解答还有一种神奇的水塘采样方法。


代码实现

Java

List存储

class Solution {
    private List<Integer> list = new ArrayList<>();
    private Random random = new Random();

    /** @param head The linked list's head.
    Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
    }

    /** Returns a random node's value. */
    public int getRandom() {
        int index = random.nextInt(list.size());
        return list.get(index);
    }
}

水塘采样

class Solution {
    private ListNode head;

    /** @param head The linked list's head.
    Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        this.head = head;
    }

    /** Returns a random node's value. */
    public int getRandom() {
        ListNode chosen = null;
        int count = 1;
        ListNode cur = head;

        while (cur != null) {
            if (Math.random() < 1.0 / count) {
                chosen = cur;
            }
            count++;
            cur = cur.next;
        }

        return chosen.val;
    }
}

发表评论

0/200
87 点赞
0 评论
收藏
为你推荐 换一批