本次有两个编程问题,一个是求两个数的和满足一定值的数目,另一个是求中位数。

2SUM问题

问题描述

The goal of this problem is to implement a variant of the 2-SUM algorithm (covered in the Week 6 lecture on hash table applications).
The file contains 1 million integers, both positive and negative (there might be some repetitions!).This is your array of integers, with the ith row of the file specifying the ith entry of the array.Your task is to compute the number of target values t in the interval [-10000,10000] (inclusive) such that there are distinct numbers x,y in the input file that satisfy x+y=t. (NOTE: ensuring distinctness requires a one-line addition to the algorithm from lecture.)

解题方法:

数据大小为1000000,对每个数都要循环一次,每个数找出匹配的y值。后面这一步是关键所在。如果使用hash把这么多数按照大小分成长度为2^15的数据段,则对于每个x只需遍历两个数据段即可,而数据是稀疏的,每个数据段之中可能只有一到两个值,这样算法复杂度就是O(N)。

具体实现如下:

from time import clock
start=clock()def myhash(val):return val>>15f=open('algo1-programming_prob-2sum.txt','r')
valnew=[True for x in range(6103503)]
tlist=[0 for x in range(-10000,10000+1)]
tmp=f.read()
f.close()
print('read complete')
vallist=[int(val) for val in tmp.split()]
vallist=set(vallist)
print('convert to set@int complete')
minval=min(vallist)
for val in vallist:val_key=myhash(val-minval)if valnew[val_key]==True:valnew[val_key]=[val]else:valnew[val_key].append(val)
print('hash complete',len(valnew),len(vallist))for val in vallist:firkey=myhash(-10000-val-minval)seckey=myhash(10000-val-minval)if firkey<len(valnew):if valnew[firkey]!=True:for tmp in valnew[firkey]:if tmp+val in range(-10000,10000+1):tlist[tmp+val+10000]=1if firkey<len(valnew):if valnew[seckey]!=True:for tmp in valnew[seckey]:if tmp+val in range(-10000,10000+1):tlist[tmp+val+10000]=1print('output: ',sum(tlist))finish=clock()
print finish-start##read complete
##convert to set@int complete
##('hash complete', 6103503, 999752)
##('output: ', ***)
##480.193410146##user@hn:~/pyscripts$ python 2sum_hash.py
##read complete
##convert to set@int complete
##('hash complete', 6103503, 999752)
##('output: ', ***)
##183.92

在win32系统下用了480s,但debian下面只需要180s。论坛有人达到0.53s,我改进的空间还很大。

中位数问题

问题描述:

The goal of this problem is to implement the "Median Maintenance" algorithm (covered in the Week 5 lecture on heap applications). The text file contains a list of the integers from 1 to 10000 in unsorted order; you should treat this as a stream of numbers, arriving one by one. Letting xi denote the ith number of the file, the kth median mk is defined as the median of the numbers x1,…,xk. (So, if k is odd, then mk is ((k+1)/2)th smallest number among x1,…,xk; if k is even, then mk is the (k/2)th smallest number among x1,…,xk.)In the box below you should type the sum of these 10000 medians, modulo 10000 (i.e., only the last 4 digits). That is, you should compute (m1+m2+m3+⋯+m10000)mod10000.

这个题除了对于每个新数组进行排序取中位数的方法外,可以采用两个heap快速的完成运算。在数据不断到来的过程中,要不断维护两个heap,使两个heap的size差不大于1,一个是最小堆,而另一个是最大堆,分别存放现有数据中较大和较小的half。

Python中只有heapq提供了最小堆,但可以对于值取反得到最大堆。

这次我实现了两种算法,速度差距很明显。实现算法:

from time import clock
from heapq import heappush,heappop
start=clock()f=open('Median.txt','r')
tmp=f.read()
f.close()
data=[int(val) for val in tmp.split()]
out=[0 for x in range(len(data))]#rudeway with high complexity
#17s running time
def rudeway(data,out):for ind in range(len(data)):b=data[0:ind+1]b.sort()out.append(b[(len(b)+1)/2-1])return sum(out)%10000#print(rudeway(data,out))#use heapq, minus(min heap)=max heap
#0.231407100855s
def heapway(data,out):lheap=[]rheap=[]out[0]=data[0]tmp=sorted(data[0:2])out[1]=tmp[0]heappush(lheap,-tmp[0])heappush(rheap,tmp[1])for ind in range(2,len(data)):if data[ind]>rheap[0]:heappush(rheap,data[ind])else:heappush(lheap,-data[ind])if len(rheap)>len(lheap):heappush(lheap,-heappop(rheap))if len(lheap)>len(rheap)+1:heappush(rheap,-heappop(lheap))out[ind]=-lheap[0]return sum(out)%10000print(heapway(data,out))finish=clock()
print finish-start

Algorithms Part 1-Question 6- 2SUM Median-数和以及中位数问题相关推荐

  1. seaborn可视化displot绘制直方图(histogram)并通过axvline函数在直方图中添加中位数(median)竖线(自定义中位数竖线的线条形式)

    seaborn可视化displot绘制直方图(histogram)并通过axvline函数在直方图中添加中位数(median)竖线(自定义中位数竖线的线条形式) 目录

  2. matlab中一组数取百分位数_GRE数学难题-正态分布+百分位数

    1 基本概念 在图标题中考察正态分布和百分位数时,通常会涉及以下基本概念 算术平均值(arithmetic) = 平均值(average) = 均值(mean) - 容易受极值影响 加权平均数 = Σ ...

  3. 【LeetCode】004 Median of Two Sorted Arrays 两个排序数组合并后的中位数

    题目:LeetCode 004 Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m an ...

  4. CF1486D Max Median

    CF1486D Max Median 题意: 给定一个长度为 n 的序列 a,求所有长度 ≥k 的连续子序列中,中位数的最大值.定义中位数是一个长度为 x 的序列升序排序后的第 ⌊x+12⌋\left ...

  5. [Swift]LeetCode480. 滑动窗口中位数 | Sliding Window Median

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ➤微信公众号:山青咏芝(shanqingyongzhi) ➤博客园地址:山青咏芝(https://www.cnblog ...

  6. 1到n中减少了一个数,顺序被打乱,找出缺失的数

    2013年的创新工场笔试考了:http://blog.csdn.net/huangxy10/article/details/8026464 而且应该还是一道经典的笔试面试题:http://fayaa. ...

  7. 两个有序数组合起来求第k小的数+左老师专访ACM大神(笔记)8月5日斗鱼直播实录

    1.长度相等的两个有序数组寻找上中位数 注:上中位数1 2 3 4 5 6为3(偶数两个中位数为前面那个) 思路:去掉不可能为上中位数的,剩下的简化组合求上中位数. 1.1 奇数序列 位置 位置 位置 ...

  8. 百亿题典之C++编程题面试题

    原文地址:百亿题典之C++编程题面试题作者:百亿题典 1. 在linked list中找倒数第N个结点 2. 倒转linked list 3. 二叉树的结点有指向parent的指针,求最近公共祖先 4 ...

  9. C++编程,数据结构,算法类面试题集

    1. 在linked list中找倒数第N个结点 2. 倒转linked list 3. 二叉树的结点有指向parent的指针,求最近公共祖先 4. 给一个数组,如何打印该数组成员构成集合的全部子集合 ...

  10. r语言中检测异常值_R中的异常值检测

    r语言中检测异常值 介绍 (Introduction) An outlier is a value or an observation that is distant from other obser ...

最新文章

  1. 6.DeepFM: A Factorization-Machine based Neural Network for CTR Prediction论文详解和代码实现
  2. dubbo学习之dubbo管理控制台装配及集成zookeeper集群部署(1)【转】
  3. pythonpandas读取csv和另外一个csv进行比较_Python Pandas:比较一个列中类似值的两个csv(dataframe)的行,并返回相似的行(列)的内容...
  4. 系统学习机器学习之算法评估
  5. mysql 建立联合索引
  6. 期望文件系统格式在“1”到“4”之间;发现格式“6”
  7. Flutter中富文件标签的解决方案
  8. 试着用React写项目-利用react-router解决跳转路由等问题(二)
  9. Eigen 简明教程之如何从Python转到Eigen
  10. 生成高清缩略图; 添加图片、文字水印; 图片、文字水印透明
  11. 埋点用例管理_API管理平台之系统设计篇
  12. domtoimage -- html转化为图片
  13. linux 汇编语言ldreq,请教一个中断句柄的问题 - ARM技术论坛-ARM嵌入式论坛-人气最火爆ARM学习论坛 - 21ic电子技术开发论坛...
  14. Makefile.am、Makefile.in、Makefile、configure.ac关系(十二)
  15. gis 空间分析 鸟类栖息地选取_鸟类的栖息地选择
  16. 威纶通触摸屏可以解密吗_【实例】西门子PLC变频器和触摸屏综合应用
  17. 实验4微程序控制器实验
  18. 搭配emuc-b202 can卡通讯时,时断时续
  19. 爵士之夜(Jazz Night)
  20. 们指点如果在android平台下开启jbox2d的debugDraw功能

热门文章

  1. java apache commons_使用java apache commons下载文件?
  2. spring boot整合shiro继承redis_Springboot+Shiro+redis整合
  3. 使用python写程序时遇到的几个小问题
  4. linux c 网络编程与信号量,linux网络编程-----线程同步--信号量
  5. cassandra随机获取数据_Cassandra维护最终一致性 和存储机制 分区策略
  6. Python练习:星号三角形 I
  7. php yii框架连接数据库,【PHP开发框架】yii框架怎样衔接数据库
  8. java继承父类执行顺序_java中子类继承父类程序执行顺序问题
  9. python中多对多替换_Python对指定文件内容进行全局替换
  10. html加载时页面闪烁白色背景,解决页面加载闪白问题-背景图片加载优化