POJ_Dynamic Median 数据流的中位数

Java实现 LeetCode 295 数据流的中位数 295. 数据流的中位数 中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。 例如, [2,3,4] 的中位数是 3 [2,3] 的中位数是 (2 + 3) / 2 = 2.5 设计一个支持以下两种操作的数据结构: void addNum(int num) - 从数据流中添加一个整数到数据结构中。 double findMedian() - 返回目前所有元素的中位数。 示... 阅读详情

Dynamic Median

总时间限制: 
3000ms 
内存限制: 
65536kB
描述

设计一个数据结构,初始为空,支持以下操作:

(1)增加一个元素,要求在log(n)时间内完成,其中n是该数据结构中当前元素的个数。注意:数据结构中允许有重复的元素。

(2)返回当前元素集合的中位数,要求在常数时间内完成。如果当前元素的个数为偶数,那么返回下中位数(即两个中位数中较小的一个)。

(3)删除中位数,要求在log(n)时间内完成。


输入
输入的第一行是一个自然数T,代表测试数据的组数((1 ≤ T ≤ 600))。每组测试数据的第一行是个自然数N,代表操作的次数,1<=N<=10000。后面的N行中的每行代表一个操作,每次操作首先输入一个单字符代表操作的类型:

I表示插入,后面跟着输入一个正整数(这是唯一带有输入数值的操作)。
Q表示查询,输出当前的中位数(这是唯一产生输出的操作)。
D表示删除当前的中位数。

输入保证是正确的:查询时集合保证不为空(即中位数是存在的),删除时保证集合中有足够可供删除的元素。
输出
每次查询操作Q时输出的中位数,每次输出单独占一行。
样例输入
1
8
I 4
I 3
I 5
Q  
D
I 10
I 2
Q
样例输出
4
3
提示
123
来源
课程

思路:这是一个剑指offer书上的一道题目。题目意思是让你找到输入的数据流中的最大的中位数,并且偶数的时候返回较小的。用两个连在一起的堆可以实现这个算法,具体是一个最大堆,一个最小堆,其中在数据插入的过程中保证最大堆的最大值要小于最小堆的最小值。这样数据被切分成了两个部分,同时保证,最大堆的size比最小堆的size大于等于1(奇数情况下),偶数情况下相等,这样 中位数是最大堆的最大值。
在删除的过程中,同时要保证堆的size信息。
数据流的题目涉及到数据量比较大,类似的题目有一个很大的数据流,去找该数据流中前k个最大的数,用一个大小为k的最小堆,这样在数据流入是保证每个数据都比最小堆的最小值小,否则就插入该元素,把之前最小的删除。
提示:!!!!!!!!!!!!!!!!!
这道题目用cin cout 会超时,不管你加不加std::ios::sync_with_stdio(false);,都会超时。

AC code:
#include <iostream>
#include<stdio.h>
#include <queue>
#include <vector>
using namespace std;
priority_queue<int, vector<int>, less<int> > p;  //最大堆
priority_queue<int, vector<int>, greater<int> > q;  //最小堆

void insert(int num){
	if(p.empty())
		p.push(num);
	else {
		if(num < p.top())
		p.push(num);
		else 
		q.push(num);
	
	}
	if(p.size() - 2 == q.size())
	{
		q.push(p.top());
		p.pop();
	}
	if(p.size() +1 == q.size()){
		p.push(q.top());
		q.pop();
	}
}
int getMedian(){
	printf("%d\n",p.top()); 
}
void deleteNum(){
	p.pop();
	if(p.size() + 1 == q.size())
	{
		p.push(q.top());
		q.pop();
	}
}
void clear(){
	while(!q.empty()) q.pop();
	while(!p.empty()) p.pop();
}
int main(){
	//freopen("B.txt","r",stdin);
	//std::ios::sync_with_stdio(false);
	int t,n,num; 
	char c;
	scanf("%d",&t);
	while(t--){
		clear();
		scanf("%d",&n); 
		while(n--){
			scanf("%c",&c);
			scanf("%c",&c);
			if(c=='I'){
				scanf("%d",&num);
				insert(num);
			}
			else if(c=='Q'){
				getMedian();
			}else {
				deleteNum();
			}				
		}
	}	
	return 0;
}



【剑指Offer】数据流中的中位数——四种解法 数据流中的中位数——四种解法题目描述:解题思路:完整代码: 题目描述: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 解题思路: 方法1:使用无序数组存储,然后需要对数组进行排序,然后就可以顺利找到中位数。 方法2:在插入数组时,就进行排序,形成有序的数组,排完序后就可以直 阅读详情

相关推荐

C#实战:如何从零构建一个轻量级软PLC梯形图编辑器(附完整源码)

本文详细介绍了如何使用C#从零开始构建一个轻量级软PLC梯形图编辑器。内容涵盖项目架构设计、GDI+图形渲染、编辑交互实现以及核心的扫描执行引擎开发,并提供了定时器、计数器等高级功能的实现思路与完整源码,为开发者深入工业自动化领域提供了实战指南。

4k5l6j7h8的博客 257

数据流中的中位数

数据流的中位数

up!up!up! 3634

GK2302量产工具下载方法,GK2302开卡教程,GK2301LT怎么开卡方法,附GK2302开卡工具,GK2301LT量产软件下载

​每种量产软件的操作流程可能略有不同,因此必须按照要求操作。为确保安全,建议使用量产部落网下载的原版量产开卡软件。

A520091000的博客 2123

OpenJudge: Dynamic Median

总时间限制:3000ms 内存限制:65536kB 描述 设计一个数据结构,初始为空,支持以下操作: (1)增加一个元素,要求在log(n)时间内完成,其中n是该数据结构中当前元素的个数。注意:数据结构中允许有重复的元素。 (2)返回当前元素集合的中位数,要求在常数时间内完成。如果当前元素的个数为偶数,那么返回下中位数(即两个中位数中较小的一个)。 (3)删除中位数,要求在log(n)时间内完成。 输入 输入的第一行是一个自然数T,代表测试数据的组数((1 ≤ T ≤ 600))。每组..

weixin_42069359的博客 209

ANSYS材料库实战:手把手教你用APDL命令流定义混凝土和形状记忆合金

本文详细介绍了在ANSYS中使用APDL命令流定义混凝土和形状记忆合金(SMA)的高级建模技巧。通过SOLID65单元和SMA本构模型,工程师可以精确模拟非线性材料行为,包括混凝土的开裂和SMA的超弹性效应。文章提供了完整的命令流示例和求解策略优化建议,帮助用户提升工程仿真效率。

hh234的博客 486

M2DGR数据集在一些SLAM框架上的配置与运行:ORB-SLAM系列、VINS-Mono、LOAM系列、FAST-LIO系列、hdl_graph_slam

为了说明以上这些SLAM框架的测试与数据集适配,以M2DGR数据集为例进行各自的配置与运行,方便我以后适配自己的数据集,运行的SLAM框架包括:ORB-SLAM2、ORB-SLAM3、VINS-Mono、A-LOAM、LeGO-LOAM、LIO-SAM、LVI-SAM、FAST-LIO2、FAST-LIVO、Faster-LIO、hdl_graph_slam。实验基于Ubuntu20.04,其中ORB、VINS-Mono、和LOAM系列的安装参考我以前的博客,有详细的安装方法,其他的框架在后面会简单介绍一下

zardforever123的博客 1万+

力扣295. 数据流的中位数

中位数是有序列表中间的数。如果列表长度是偶数,中位数则是中间两个数的平均值。 例如, [2,3,4] 的中位数是 3 [2,3] 的中位数是 (2 + 3) / 2 = 2.5 设计一个支持以下两种操作的数据结构: void addNum(int num) - 从数据流中添加一个整数到数据结构中。 double findMedian() - 返回目前所有元素的中位数。 示例: addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian()

宫浩然的博客 626

【Bug已解决】claude: No such file or directory — Claude Code 命令凭空消失解决方案

方案适用场景推荐指数难度方案一:重建软链接所有平台,软链接断裂⭐⭐⭐⭐⭐低方案二:修复 shebangnvm 用户,不想重装⭐⭐⭐⭐中方案三:nvm default aliasnvm 用户,长期稳定⭐⭐⭐⭐低方案四:切换到 Volta频繁切换 Node.js 版本⭐⭐⭐中方案五:修复 PATHPATH 配置丢失⭐⭐⭐⭐低方案六:Homebrew 安装macOS 用户,npm 不稳定⭐⭐⭐⭐低根本原因与。

博客 1万+

算法的学习笔记—数据流中的中位数(牛客JZ41)

这种使用双堆(大顶堆和小顶堆)的方法使得我们能够高效地从数据流中计算中位数。由于堆结构的特性,插入元素和获取中位数的时间复杂度都为O(log n),满足了题目对时间复杂度的要求。这种方法不仅适用于题目给定的范围,还可以扩展到更大规模的数据流处理中。😁热门专栏推荐想学习vue的可以看看这个java基础合集数据库合集redis合集nginx合集linux合集手写机制微服务组件spring_尘觉springMVCmybits🤔欢迎大家加入我的社区尘觉社区。

业精于勤,荒于嬉 1532

实验2 存储器设计与实现【计算机组成原理】

实验2 存储器设计与实现【计算机组成原理】

小心星的博客 2398

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

leetcode:295. 数据流的中位数

比如,我们依次添加 [1, 2, 3, 4, 5],砍成两半之后为 [1, 2] 和 [3, 4, 5],我们只要能快速的找到 2 和 3 即可。相当于,把所有元素分成了 大 和 小 两半(两个堆的大小最多相差1),而我们计算中位数,只需要 大的那半的最小值 和 小的那半的最大值即可。中位数的题,我们一般都可以用 大顶堆 + 小顶堆来求解,下面我们详细来解释一下。......

OceanStar的博客 807

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

poj 3784 用堆动态求解中位数

堆真是一种简单而又神奇的数据结构,以前用它求过前kth的数,现在又可以用两个堆来动态求解中位数。 算法:   构建一个大顶堆和一个小顶堆,分别记为g和l。   假设当前中位数为mid,新读入一个数为tmp,则:   1.如果tmp < mid,则将tmp插入大顶堆,跳到步骤3。   2.如果tmp >= mid,则将tmp插入小顶堆,跳到步骤4。   3.如果大顶堆的元素个...

weixin_30642305的博客 196

深度学习工具包 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")

基于Flink+Kafka+Hadoop+Hive的智能物流大数据平台实战

大数据技术栈是现代企业处理海量数据、实现实时洞察的核心引擎。其核心原理在于通过分布式架构,将数据采集、存储、计算与分析解耦,以应对高并发、低延迟的业务需求。在技术价值层面,它能够将传统批处理无法满足的实时监控、智能预测变为现实,极大地提升了业务决策的敏捷性与准确性。典型的应用场景包括电商实时推荐、金融风控和物联网设备监控。本文聚焦于物流行业,针对实时监控运单状态、预测运输时长与智能路线推荐等核心需求,详细阐述了如何整合Flink、Kafka、Hadoop和Hive等组件,构建一个集实时计算与离线分析于一体的

weixin_33766168的博客 400

数组流中的中位数

如何找到数组流中的中位数 题目 数据流中的中位数 如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值; 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值; 分析 如果数组在容器中已经排序,那么中位数可以由p1和p2指向的数得到;如果容器中数据的数目是奇数,那么p1和p2指向同一个数据; 我们注意到整个数据容器被分割成两部分...

小太阳 670

数据流的中位数

优质博文。

程序猿进阶 1083

动态中间值的查找(dynamic median finding)

问题描述     从一组无序的数组里求它的中间值,要求定义一个数据结构,保证用常量的时间可以找到中间值,而插入一个元素的时间复杂度为O(logn),而删除中间值元素的时间复杂度为O(logn)。这个问题要求里最严格的一点是,以上的这些特性的保持是动态的。比如说,我们要输入的元素可能有1000个,但是在我输入前面的若干个元素的时候,它们也满足以上的特性。   分析     在分析这个问题...

点缀星辰 1729

POJ-3579中位数(STL解题)

stl解题

weq2011的博客 982

数据流中的中位数(C++)

数据流中的中位数 描述   如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。 数据范围:数据流中数个数满足1≤n≤1000,大小满足1≤val≤1000 进阶: 空间复杂度 O(n) , 时间复杂度 O(nlogn) 示例1 输入: [5,2,3,4,1,6,7,0,8] 返回

田螺姑娘的博客 768

算法进阶——数据流中的中位数

对于求动态中位数的问题,利用堆的性质,可以在O(nlogn)的时间复杂度取出最大值或最小值,那么我们可以用大顶堆维护前一半的数,用小顶堆维护后面一半的数。

吴尼玛cs 812
上一篇: POJ_Butterfly
下一篇: poj 丛林中的树
lxt_bupt
博客等级 码龄12年 31粉丝 19原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值