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

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>>15 f=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]=1
if firkey<len(valnew):
if valnew[seckey]!=True:
for tmp in valnew[seckey]:
if tmp+val in range(-10000,10000+1):
tlist[tmp+val+10000]=1 print('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)%10000 print(heapway(data,out)) finish=clock()
print finish-start

Algorithms Part 1-Question 6- 2SUM Median-数和以及中位数问题的更多相关文章

  1. POJ 3784 Running Median(动态维护中位数)

    Description For this problem, you will write a program that reads in a sequence of 32-bit signed int ...

  2. c++ question 003 求两数大者?

    #include <iostream>using namespace std; int main(){ //求两数中的大者? int a,b; cin>>a>>b; ...

  3. 【HackerRank】Find the Median(Partition找到数组中位数)

    In the Quicksort challenges, you sorted an entire array. Sometimes, you just need specific informati ...

  4. URAL 1306 - Sequence Median 小内存求中位数

    [题意]给出n(1~250000)个数(int以内),求中位数 [题解]一开始直接sort,发现MLE,才发现内存限制1024k,那么就不能开int[250000]的数组了(4*250000=1,00 ...

  5. POJ 3579:Median 差值的中位数

    Median Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 4680   Accepted: 1452 Descriptio ...

  6. POJ 3784 Running Median【维护动态中位数】

    Description For this problem, you will write a program that reads in a sequence of 32-bit signed int ...

  7. LeetCode295-Find Median from Data Stream && 480. 滑动窗口中位数

    中位数是有序列表中间的数.如果列表长度是偶数,中位数则是中间两个数的平均值. 例如, [2,3,4] 的中位数是 3 [2,3] 的中位数是 (2 + 3) / 2 = 2.5 设计一个支持以下两种操 ...

  8. [leetcode]295. Find Median from Data Stream数据流的中位数

    Median is the middle value in an ordered integer list. If the size of the list is even, there is no ...

  9. 光圈与F数相关知识

    一.F数 F数.光圈数.相对孔径的倒数. F数代表的意义 F数小(光圈大).F数大(光圈小). F数又称为镜头速度,F数小的镜头速度快.因为拍摄的曝光时间△t 正比于F数的平方. F数还能表征镜头的分 ...

  10. 1005E1 Median on Segments (Permutations Edition) 【思维+无序数组求中位数】

    题目:戳这里 百度之星初赛原题:戳这里 题意:n个不同的数,求中位数为m的区间有多少个. 解题思路: 此题的中位数就是个数为奇数的数组中,小于m的数和大于m的数一样多,个数为偶数的数组中,小于m的数比 ...

随机推荐

  1. 基于XMPP的即时通信系统的建立(四)— 组件介绍

    服务端 服务器 许可证 操作系统 是否支持任意客户端登录 备注 ejabberd 开源 Elang 是 支持虚拟主机和集群 Openfire Apache Java 是 Tigase GPLv3 Ja ...

  2. Java I/O 扩展

    Java I/O 扩展 标签: Java基础 NIO Java 的NIO(新IO)和传统的IO有着相同的目的: 输入 输出 .但是NIO使用了不同的方式来处理IO,NIO利用内存映射文件(此处文件的含 ...

  3. linux + ffmpeg + eclipse 调试

    使用linux + ffmpeg + eclipse调试步骤OS : ubuntu 12.04Eclipse : 3.7.2 为Eclipse安装cdt插件,使其支持c/c++ 导入ffmpeg项目 ...

  4. ZOJ 1455 Schedule Problem(差分约束系统)

    // 题目描述:一个项目被分成几个部分,每部分必须在连续的天数完成.也就是说,如果某部分需要3天才能完成,则必须花费连续的3天来完成它.对项目的这些部分工作中,有4种类型的约束:FAS, FAF, S ...

  5. 【转】Github轻松上手1-Git的工作原理与设置

    转自:http://blog.sina.com.cn/s/blog_4b55f6860100zzgp.html 作为一个程序猿,如果没有接触过stack overflow和Github,就如同在江湖中 ...

  6. Android studio 下JNI编程实例并生成so库

    Android studio 下JNI编程实例并生成so库 因为公司需要为Android相机做美颜等图像后期处理,需要使用JNI编程,最近学了下JNI,并且在Android Studio下实现了一个小 ...

  7. 应用emailAutoComplete.js来自动显示邮箱后缀列表

    我们经常有邮箱的人都特别清楚,在输入我们的邮箱时,会自动显示出邮箱后缀列表,这个用户体验是不错的. 操作据悉——当我们输入文字时,会自动有个邮箱后缀名的列表.      而我这边的代码是,应用jque ...

  8. Linux--使用expect进行自动交互

    在linux下进行一些操作时,有时需要与机器进行一些交互操作,比如切换账号时输入账号密码,传输文件时输入账号密码登陆远程机器等,但有时候这些动作需要在shell脚本中进行,这个时候就可以使用expec ...

  9. 【windows核心编程】一个API拦截的例子

    API拦截 修改PE文件导入段中的导入函数地址 为 新的函数地址 这涉及PE文件格式中的导入表和IAT,PE文件中每个隐式链接的DLL对应一个IMAGE_IMPORT_DESCRIPTOR描述符结构, ...

  10. rfid门禁系统笔记

    非接触式IC卡性能简介 主要指标: 1:容量为8K 位的EEPROM 2:分为16个扇区,每个扇区为4块,每块16个直接,以块为存取单位 3:每个扇区有独立的一组密码和访问控制 4:每张卡具有唯一的序 ...