[LeetCode] 382. Linked List Random Node

发布时间:2019-07-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 382. Linked List Random Node脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

PRoblem

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

Solution

class Solution {

    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    ListNode head;
    Random random;
    public Solution(ListNode head) {
        this.head = head;
        random = new Random();
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode cur = head;
        int res = cur.val, count = 1;
        while (cur.next != null) {
            cur = cur.next;
            if (random.nextInt(count+1) == count) {
                res = cur.val;
            }
            count++;
        }
        return res;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 382. Linked List Random Node全部内容,希望文章能够帮你解决[LeetCode] 382. Linked List Random Node所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。