题目要求:

Download the text file here. (Right click and save link as).

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.)

Write your numeric answer (an integer between 0 and 20001) in the space provided.

OPTIONAL CHALLENGE: If this problem is too easy for you, try implementing your own hash table for it. For example, you could compare performance under the chaining and open addressing approaches to resolving collisions.

大致意思是说,有一百万个数字(正负都有,且可能重复)。目标是要寻找到两个数x和y,使得x+y属于[-10000, 10000]的范围中,且x和y在所有数当中都是唯一存在的,最后输出所有可能的和的个数。

文件中的数据差不多是这样子的:

...
-92205919974
-65150999169
-96247986144
70191728682
-59670982771
-10202710755
-72167080349
-19221613985
80341418823
-79433686277
87351713416
6084932343
40801752610
44028247959
84203784346
-28120386474
59064431376
39436465566
-89458683408
-64200776240
-42582579303
-62656888535
55650079602
62954175548
33713639217
70259349593
-97472959477
41890148139
44216212976
26864335558
...

解题思路:

起初采用了最暴力的方法,直接把这些数字塞进一个hash table中,然后遍历着去查询(这个方法很不好,所以就不详述了),结果运行了很久都没有跑出结果,遂直接放弃这种方法。

这里的问题在于如下两点:

  1. 数据量多达一百万条;
  2. 大部分数对相加的和,远超要求的范围之外。

因此针对问题的实际情况进行了些许优化,大致思路如下:

  1. 假设X为文件中的一个数字;
  2. 创建一个hash table,它的键为X/10000,值为由对应X组成的set。这样就相当于把输入的数据以10000作为一个范围对其进行划分,最后划分成若干组数据,之所以要将10000作为划分的范围,是因为题目中要求数对的和在[-10000, 10000]的范围中,这样对于我们这里的hash table,给定一个key1,我们就能知道可能有哪些key2对应集合中的数与key1集合中的数相加,是可以在要求的范围中的;
  3. 具体而言,对于一个key1,可取的key2有:{-key1-2, -key1-1, -key1}这三个。注意因为之前的X/10000是整除,其结果为向下取整,如 -14000 / 10000 = -2;
  4. 在已知了key1与key2之后,对其集合中的数进行循环遍历,如果相加的和在题目要求的范围内,那么就将计数器加一。

利用上述思路,可以避免大量的不必要的运算,另外我们还可以对其进行进一步的优化:

  1. 对key1进行遍历的时候,只取key1小于或等于零的值,这样可以进一步减少重复计算;
  2. 创建一个保存结果的set,如果找到了满足要求的数对(x, y),那么就置result[x+y] = True,最后输出result的大小。

代码实现:

有了上述的思路,利用Python对其进行了实现,代码如下:

result = {}
dic = {}
input_file = open("algo1-programming_prob-2sum.txt") # 读入数据
for line in input_file:
num = long(line)
key = num/10000
if key not in dic:
dic[key] = {}
# 这里记录数据出现的次数,用来判断该数是否是唯一的
if num in dic[key]:
dic[key][num] += 1
else:
dic[key][num] = 1 for key1 in dic:
# 忽略key1 > 0的情况,减少不必要的重复计算
if key1 > 0:
continue
# 根据给定的key1,可以推测出key2可取的值
for key2 in range(-key1-2, -key1 + 1):
if key2 in dic:
# 对key1和key2对应集合中的数进行遍历
for value2 in dic[key2]:
for value1 in dic[key1]:
# 判断这两个数是否是唯一的
if dic[key1][value1] != 1 or dic[key2][value2] != 1:
continue
sum_tmp = value1+value2
# 判断两数之和是否在题目要求的范围内
if abs(sum_tmp) <= 10000 and sum_tmp not in result:
result[sum] = True # 输出结果
print len(result)
input_file.close()

这段代码在我的电脑上运行仅需要大约3-4秒的时间就能跑出结果(包含读取数据的I/O操作的时间),可见该方法有效地避免了大量不必要的计算。

另外,题目中要求找到唯一存在的数对(x, y),但是如果把代码中判断唯一性的那个条件判断去除,得到的结果也是一样的,这也许和给出的数据有关。

一个"2-SUM"问题的更多相关文章

  1. [LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

  2. [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:add and find. add - ...

  3. 数字和为sum的方法数

    [编程题] 数字和为sum的方法数 给定一个有n个正整数的数组A和一个整数sum,求选择数组A中部分数字和为sum的方案数. 当两种选取方案有一个数字的下标不一样,我们就认为是不同的组成方案. 输入描 ...

  4. ✡ leetcode 170. Two Sum III - Data structure design 设计two sum模式 --------- java

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  5. 求和函数 sum详解

    sum()的参数是一个list: >>> sum([1,2,3]) 6 >>> sum(range(1,3)) 3 还有一个比较有意思的用法 a = range(1 ...

  6. Sum 类型题目总结

    Sum类的题目一般这样: input: nums[], target output: satisfied arrays/ lists/ number 拿到题目,首先分析: 1. 是几个数的sum 2. ...

  7. hdu 3415 Max Sum of Max-K-sub-sequence(单调队列)

    题目链接:hdu 3415 Max Sum of Max-K-sub-sequence 题意: 给你一串形成环的数,让你找一段长度不大于k的子段使得和最大. 题解: 我们先把头和尾拼起来,令前i个数的 ...

  8. LeetCode OJ 209. Minimum Size Subarray Sum

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  9. LeetCode算法题-Sum of Left Leaves(Java实现)

    这是悦乐书的第217次更新,第230篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第85题(顺位题号是404).找到给定二叉树中所有左叶的总和.例如: 二叉树中有两个左叶 ...

  10. item 6: 当auto推导出一个不想要的类型时,使用显式类型初始化的语法

    本文翻译自<effective modern C++>,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 Item 5解释了比起显式指定类型,使用auto来 ...

随机推荐

  1. tomcat启动一闪而过问题的解决

    1.今天使用startup.bat启动tomcat报错,现象是一闪而过,在logs文件夹中有没有日志文件, 可以在控制台输入startup.bat,如下:   但是也没有看出什么太有用的错误,然后可以 ...

  2. Vuejs实例-02Vue.js项目集成ElementUI

    Vuejs实例-02Vue.js项目集成ElementUI 0:前言 vue.js的UI组件库,在git上有多个项目,我见的使用者比较多的是iView和Element.两个组件库,组件都很丰富. 官网 ...

  3. 我来说说XML文件中的xmlns、xmlns:xsi和xsi:schemaLocation的具体含义

      文章摘自:https://yq.aliyun.com/articles/40353               http://www.cnblogs.com/zhao1949/p/5652167. ...

  4. Spring Cloud 客服端负载均衡 Ribbon

    一.简介   Spring Cloud Ribbon 是一个基于Http和TCP的客服端负载均衡工具,它是基于Netflix Ribbon实现的.它不像服务注册中心.配置中心.API网关那样独立部署, ...

  5. 面试(4)-spring-Spring面试题和答案

    1:69道Spring面试题和答案 转自:http://ifeve.com/spring-interview-questions-and-answers/ 目录 Spring 概述 依赖注入 Spri ...

  6. Nginx+Tomcat+MemCached 集群配置手册

    系统实施文档 Nginx+Tomcat+MemCached 集群配置手册 目    录 第1章   概述 1.1   目标 互联网的快速发展带来了互联网系统的高负载和高可用性, 这要求我们在设计系统架 ...

  7. spring-线程池(1)

    多线程并发处理起来通常比较麻烦,如果你使用spring容器来管理业务bean,事情就好办了多了.spring封装了java的多线程的实现,你只需要关注于并发事物的流程以及一些并发负载量等特性,具体来说 ...

  8. 教育类APP开发现新增长,多款APP该如何突围?

    "十二五"以来,国家共出台相关的重大教育政策文件741个,而进入到"十三五"时期教育领域综合改革深入推进的关键期,不断促进教育现代化的实现.加快迈入人力资源强国 ...

  9. C语言之运算符和条件结构

    表达式:是有操作数和运算符组成的. 操作数:常量.变量.子表达式 X=(x+2)*(y-2); 运算符: 赋值运算符:= .其作用是做赋值运算,将等号后边的值赋值给等号前边的. 复合赋值运算符: += ...

  10. 每天一个JS 小demo之商品下架特效制作,主要知识点:定时器,倒计时,抖动特效。PS:由于不方便上传文件夹,只能上传效果图,图片等素材需自寻哟。

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...