zoukankan      html  css  js  c++  java
  • 382. Linked List Random Node

    主要就是后FOLLOW UP,如何在不知道总数的情况下,随机选取。

    用的是沼气池理论,貌似是统计那块的。

    if (rdm.nextInt(base) == 0) res = temp.val;
    

    这行的意思是,还是遍历,但是对于某个节点,被选到的几率是1/x,比如第四个,被选中的概率是1/4,但是我们此时不停止遍历,继续遍历,如果以后选中别的,刚才被选中的第四个会被覆盖,所以为了保证第4个被选中,后面必须不被选中,那概率就是:
    1/4 * 4/5 * 5/6 ... n-1/n

    对于某一个点X,不被选中的概率是x-1/x。

    最后乘下来正好是1/n

    public class Solution {
    
        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() 
        {
            Random rdm = new Random();
            
            int res = -1;
            
            // 1/4 * 4/5 * 5/6... n-1/n
            ListNode temp = head;
            for (int base = 1; temp != null; base++, temp = temp.next) 
            {
                if (rdm.nextInt(base) == 0) res = temp.val;
            }
                
            return res;
        }
    }
    
  • 相关阅读:
    asp.net 启动关闭iis
    vue 界面关闭触发事件 ---实例销毁之前调用
    ElmentUI 设置禁止点击遮罩关闭 el-dialog 弹窗
    C#反射
    SQL Server 创建游标(cursor)
    文件解压缩
    文件流操作
    Linq查询
    C#线程 多线程 进程
    匿名类型和反射
  • 原文地址:https://www.cnblogs.com/reboot329/p/5912465.html
Copyright © 2011-2022 走看看