382. Linked List Random Node (蓄水池抽样,java)

STM8库函数开发手册(3) //UART1、内部EEPROM、FLASH操作库、IIC(硬、软) STM8S 微控制器家族的通用同步异步收发器(UART1,UART2 或者UART3)提供了一种灵活的方法与使用工业标准NRZ 异步串行数据格式的外部设备之间进行全双工数据交换。STM8 的UART 提供范围的波特率选择,并且支持多处理器通讯。UART 也支持LIN(局部互联网)协议版本1.3,2.0,和2.1 以及在主模式下的J2602。 UART1 和UAR... 阅读详情

382. Linked List Random Node

  • Total Accepted: 23716
  • Total Submissions: 51037
  • Difficulty: Medium
  • Contributor: LeetCode

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

Subscribe to see which companies asked this question.


题目链接:https://leetcode.com/problems/linked-list-random-node/#/description

解题思路:题目意思是给定一个链表,随机输出链表中的一个数,要求每个数输出的概率相等。蓄水池抽样可定义为:在不知总个数的情况下,等概率地抽取这组数中的某个数。核心思想是:1、初始答案为第一个数,此时链表的下标指向第一个数,即此时第一个数被选中的概率为1;

                      2、下标后移一位指向第二个数,用Random函数随机抽取0-1的数,抽取的范围是2,抽中1的概率为1/2,如果抽中1,把答案改为此时下标所指的数,否则不改变答案的值。

                      3、以此类推,用Random函数抽取的范围不断加1,即Random rd = new Random(i),抽取范围为i,从0 -( i-1)中取道 i-1 的概率为1 / i。如果抽中i-1,把答案改为此时下标所指的数,否则不改变答案的值。

                      4、直到链表为空,得到答案;

第 i 个数被选中的概率为它被选中的概率:1 / i ,乘以后面的数不被选中的概率:[ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n  - 1 ) / ( n + 1 )]

即P(第 i 个数被选中) = (  1 / i  )* [ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n  - 1 ) / ( n + 1 )] = 1 / n


代码如下:

(leetcode提交代码)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {

    static ListNode h = null;
    /** @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.h = head; 
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        Random rd = new Random ();
        int ans = -1;
        int idx = 0;
		ListNode p = h;
        while(p!=null){
        	idx++;
        	int rn = rd.nextInt(idx);
        	if(rn==idx-1){
        		ans = p.val;
        	}
        	p = p.next;
        }
        return ans;
    }
}

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

eclipse 上代码:

import java.util.Random;

public class Main {

	static class ListNode {
		      int val;
		      ListNode next;
		      ListNode(int x) 
		      { val = x; }
		  }
	static ListNode h = null;
    public Main(ListNode head) {
        this.h = head; 
    }
    public static int getRandom() {
        Random rd = new Random ();
        int ans = -1;
        int idx = 0;
		ListNode p = h;
        while(p!=null){
        	idx++;
        	int rn = rd.nextInt(idx);
        	if(rn==idx-1){
        		ans = p.val;
        	}
        	p = p.next;
        }
        return ans;
    }
    public static void main(String[] args){
    	ListNode head = new ListNode(1);
    	head.next = new ListNode(2);
    	head.next.next = new ListNode(3);
    	Main obj = new Main(head);
    	System.out.println(obj.getRandom());
    }
}



高通Camx架构调试不求人:手把手教你开UMD/KMD Log与Dump图像(附离线Log合成脚本) 本文详细介绍了高通Camx架构的调试方法,包括UMD/KMD Log的精准配置与图像Dump技术,帮助工程师快速定位移动影像系统中的问题。通过实战案例和自动化脚本,提升调试效率,适用于图像色彩异常、帧率波动等常见问题的诊断与解决。 阅读详情

相关推荐

【生产实践】SSH服务弱加密算法修复指南(附完整操作流程)

SSH服务弱加密算法漏洞修复方案 检测发现SSH服务存在支持弱加密算法漏洞,主要风险包括: 使用arcfour、aes128-cbc等易被破解的算法 面临密钥恢复、重放攻击等安全威胁 提供两种修复方案: 推荐方案:升级OpenSSH至最新版本 替代方案:修改SSH配置禁用弱算法(需注意可能影响旧客户端连接) 修复步骤: 编辑/etc/ssh/sshd_config 注释或删除弱算法配置 添加强加密算法(如aes128-ctr等) 重启SSH服务 注意事项: 建议先在测试环境验证 可能需配合客户端升级 操作前

SunMy的博客 3132

蓄水池抽样算法(reservoir sampling)

> 场景:在**长度未知**的数据流中,**等概率**地采样一定数量的数据。即,数据量N未知,若要求采样k个数据,采样概率保证$\frac{k}{N}$。 > > 要求:只遍历一遍数据,空间复杂度:$O(N)$。 > > 内容提要:算法主要思想、证明、LeetCode真题、Java源码。

Wdradon的博客 3699

沐数科技数据开发岗笔试题2025

与数据库中的主键(Primary Key)​有所不同,业务主键(Business Key)​是业务层面的唯一标识,通常由业务规则决定,例如,订单号、订单明细号,身份证号等。用户授信表(table_credit):包含用户ID(uid)、授信申请时间(credit_submit_time_local)、授信状态(credit_status)。:在正态分布中,大约68%的数据值落在距离均值一个标准差的范围内,约95%的数据值落在两个标准差的范围内,而约99.7%的数据值落在三个标准差的范围内。

weixin_40121264的博客 3533

随机取样已死,蓄水池抽样称王

最近小黄的朋友去一家业内有名的游戏公司面试,出了一道经典的题目:目前游戏需进行一项签到抽奖的活动,怎么保证每个人抽到奖品的概率都是相等的,保证最终中奖的人数为10人。

爱敲代码的小黄 3934

【论文复现】自动化细胞核分割与特征分析

HoVer-Net是一种精心设计的多分支深度学习网络架构,专为处理复杂的多组织显微图像中的细胞核实例分割与精确分类任务而开发。该网络通过创新的策略,不仅有效解决了细胞核在密集聚集区域难以准确区分的问题,还实现了对每个独立细胞核类型的细致分类。此外,HoVer-Net还引入了专门的上采样分支,这一设计旨在对每个成功分割出的细胞核实例进行进一步的核类型分类。这一分支利用高级语义信息,结合精心设计的分类策略,能够准确判断每个细胞核的所属类型,为医学研究提供了宝贵的细胞水平信息。

2201_75366661的博客 1983

EMD-LSTM时序预测 | MATLAB实现基于EMD-LSTM时间序列预测(EMD分解结合LSTM长短期记忆神经网络)

EMD-LSTM时序预测 | MATLAB实现基于EMD-LSTM时间序列预测(EMD分解结合LSTM长短期记忆神经网络)

机器学习之心的博客,关注并私信文章链接,获取对应文章源码和数据。 673

Linked List Random Node

Linked List Random Node Question: 思路: 这道题乍一看, 挺简单的. 没什么难度, 确实,但这题主要是一个解法非常smart. so: generally 3种解法. 前两种不必多说了, 说一下这个第三种解法: reservoir sampling. 这是一个很牛逼的算法。 讲的是如何从infintine number 的data中 随机抽取一个数. 就前提条件是这个 array of number的长度我们是未知的。就是说不知道有多少个数字, 所以在这种情况下. 如果

weixin_44912492的博客 202

拆解全球18大“支付清算”体系:CLS、中国、美国、欧洲、日本、mBridge...

拆解全球18大“支付清算”体系:CLS、中国、美国、欧洲、日本、mBridge...

银行信息系统应用架构详解 899

382.[LeetCode]Linked List Random Node(蓄水池算法)

参考资料:非常的好的文章,一看就会此题要使用的是 经典的蓄水池算法,该方法的使用场景是 数据流长度未知,要求随机public class Solution { private ListNode head; /** @param head The linked list's head. Note that the head is guaranteed to be not n

薛昭君的博客 594

【系统架构设计师】预测试卷四:综合知识(75道选择题)

本文整理系统架构设计师考试高频考点,涵盖计算机系统基础、计算机网络、数据库、软件工程与UML四大模块,共28道典型题目。重点解析Cache局部性原理、RISC/CISC区别、TCP三次握手、B+树索引优势、CAP定理、螺旋模型特点等核心概念,并标注易错选项,帮助考生快速掌握解题思路。 关键词:系统架构、Cache、RISC、TCP、B+树、CAP定理、螺旋模型

数据知道的博客 563

AgentScope Java 2.0 项目实战:从零构建企业级自主Coding Agent

本文基于 AgentScope Java 框架,完整拆解两个生产级 AI Agent 项目的从零开发全过程。其一是企业级自主编码机器人(agentscope-codingagent),支持 Issue→PR 自动实现、PR Code Review、Docker 沙箱隔离执行与多通道接入;其二是个人 AI 助手管理平台(agentscope-paw),采用 Spring Boot + React 全栈架构,支持多 Agent、技能市场与多 IM 通道。

program哲学 859

java 随机抽取List数据

Java 随机抽取集合数据

南国以南i的博客 969

WPF用户控件间属性传递的艺术

本文详细介绍了WPF中父控件向子控件传递属性的方法。针对常见的绑定失效问题,重点讲解了使用RelativeSource绑定技术,通过指定AncestorType确保正确访问父控件属性。文章通过实例演示了从ParentModel传递属性到ChildUserControl依赖属性的完整实现过程,包括模型定义、XAML结构设计和代码实现。这种方法有效解决了数据上下文混淆问题,为WPF开发中的控件交互提供了可靠解决方案,有助于提升应用的灵活性和可维护性。

2501_90323865的博客 63

LeetCode:382 Linked List Random Node蓄水池抽样算法

问题定义 长度为N的链表,N很大,但是不知道具体有多大。从N个元素中随机取出K个元素,只能遍历一次链表。用到的算法保证取出的元素恰好有K个,且他们是完全随机的(出现概率均相等)。 求解 该算法是针对从一个序列中随机抽取不重复的K个数,保证每个数被抽取到的概率为k/n这个问题而构建的。做法是: 首先构建一个可放K个元素的蓄水池,将序列的前K个元素放入蓄水池中。然后从第K+1个元素开始

andy_gfz的博客 864

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

leetcode382 Linked List Random Node java

DescriptionGiven 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

店小不二的博客 514

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

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

淡然坊 232

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

LeetCode:382 Linked List Random Node

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.

Wisimer 1009

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 i

学渣记事本 214

LeetCode 382. Linked List Random Node 题解

本题是蓄水池抽样算法的经典应用。蓄水池抽样:以 1/i 的概率选择第 i 个元素数学证明:每个元素最终被选中的概率都是 1/n时间-空间权衡:可以预先存储所有值来优化查询通过本题可以深入理解蓄水池抽样算法在大数据流处理中的应用。

cannonjinx的博客 4309

JAVA学习-蓄水池抽样算法

生活中无时不刻都在发生着随机事件,我们并不能改变它的随机性,但是我们可以尝试利用它的概率去做更多有意义的事情。比如有一个高 10 米的蓄水池,我们需要对随机一个 1 米的水层进行抽样,这时候很多人都会想到直接生成一个 (0, 10] 的随机数就可以解决,那么要是把高 10 米的条件去掉呢?这显然就不是一个随机数就能解决的了,这时候就得轮到今天的主角——蓄水池抽样算法登场了。 蓄水池抽样算法是一种不用知道蓄水池深度就可以达到抽样效果的算法,他的核心在于按每一层循序依次进行抽样,不同层的抽样计算如下: 如果

qq_48772498的博客 1141

java实现list均匀采样算法

java实现list均匀采样算法,从一个List对象中均匀抽选出固定数量的样本。

qq_36635569的博客 1516

Linked List Random Node 链表随机节点

给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。 进阶: 如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现? 示例: // 初始化一个单链表 [1,2,3]. ListNode head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ...

qq_26410101的博客 542

Halcon深度学习实战:用猫狗分类项目带你从数据整理到模型部署(附完整代码)

本文详细解析了Halcon深度学习在工业视觉检测中的应用,从数据准备到模型部署的全流程。通过猫狗分类项目实战,重点介绍了工业级数据组织、Halcon特有API设计及超参数调优策略,帮助开发者高效实现分类模型训练与部署,提升工业场景下的视觉检测效率。

weixin_30621959的博客 220

[leetcode] 382. Linked List Random Node 解题报告

题目链接: https://leetcode.com/problems/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 chose

小榕流光的专栏 4890
上一篇: 历届试题 剪格子 (DFS,java)
下一篇: leetcode 242. Valid Anagram
雨狮子
博客等级 码龄12年 24粉丝 185原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值