zoukankan      html  css  js  c++  java
  • [LeetCode] 382. Linked List Random Node ☆☆☆

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

    解法: 

      由于无法确定链表的长度,或者链表的长度很长,因此需要采用水塘抽样算法。由于限定了head一定存在,所以我们先让返回值res等于head的节点值,然后让curr指向head的下一个节点,定义一个变量count,初始化为1,若curr不为空我们开始循环,我们在[0, count)中取一个随机数,如果取出来0,那么我们更新res为当前的curr的节点值,然后此时count自增一,curr指向其下一个位置,这里其实相当于我们维护了一个大小为1的水塘,然后我们随机数生成为0的话,我们交换水塘中的值和当前遍历到底值,这样可以保证每个数字的概率相等,参见代码如下:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public 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() {
            int count = 1;
            int res = head.val;
            ListNode curr = head.next;
            while (curr != null) {
                if (new Random().nextInt(++count) == 0) {
                    res = curr.val;
                }
                curr = curr.next;
            }
            return res;
        }
    }
    
    /**
     * Your Solution object will be instantiated and called as such:
     * Solution obj = new Solution(head);
     * int param_1 = obj.getRandom();
     */
  • 相关阅读:
    参考资料
    利用docker compose启动gitlab及runner
    在gitlab上setup CI
    git ssh端口号变更之后所需要的修改
    使用Docker Image跑Gitlab
    用Docker Compose启动Nginx和Web等多个镜像
    .NET core mvc on Docker
    ubuntu 挂载windows共享目录的方法
    13-14 元旦随想
    Uva 10177 (2/3/4)-D Sqr/Rects/Cubes/Boxes?
  • 原文地址:https://www.cnblogs.com/strugglion/p/6425684.html
Copyright © 2011-2022 走看看