2-SUM algorithm
来源:互联网 发布:js 页面跳转 禁止后退 编辑:程序博客网 时间:2024/04/29 06:40
The file contains 1 million integers, both positive and negative (there might be some repetitions!).This is your array of integers, with the
Your task is to compute the number of target values
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.
这个不知道怎么用Hash实现,只采用了一种简单的实现:
// Reference: http://tech-wonderland.net/blog/summary-of-ksum-problems.html#include <iostream>#include <fstream>#include <math.h>#include <vector>#include <sstream>#include <set>using namespace std;bool Sum2(set<__int64> &inputs, int target){set<__int64>::iterator itBeg;set<__int64>::iterator itEnd;itBeg = inputs.begin();itEnd = inputs.end();itEnd--;__int64 sum;bool result = false;while(itBeg != itEnd) {sum = *itBeg + *itEnd;if (sum == target){result = true;break;}else if (sum < target){itBeg++;}else{itEnd--;}}return result;}int main(){ifstream infile;infile.open("algo1-programming_prob-2sum.txt");set<__int64> inputSet;__int64 input;while(!infile.eof()){infile >> input;inputSet.insert(input);}int sum =0;for (int i=-10000; i<10001; i++){if (Sum2(inputSet, i)){sum++;}}cout << "The number is " << sum << endl;infile.close();return 0;}
参考:
[1] Summary for leetcode 2Sum, 3Sum, 4Sum, K Sum http://tech-wonderland.net/blog/summary-of-ksum-problems.html
- 2-SUM algorithm
- Leetcode Algorithm 001. Two Sum
- Algorithm 2
- 【Leet Code- Algorithm】【1-Two Sum】【Python】
- Leetcode Algorithm 416. Partition Equal Subset Sum
- Algorithm Arrays-3 Max Sum Contiguous Subarray
- Algorithm之路一:Two Sum
- Algorithm之路十五:3Sum
- Algorithm之路十六:3Sum Closest
- Algorithm之路十八:4Sum
- 002-algorithm-max len sub list with maximum sum
- !!!Chapter 2 Algorithm Analysis
- PageRank Algorithm (2)
- Smarking Algorithm Contest 2
- STL algorithm -2
- Algorithm-Arrays-2
- ALGORITHM 4.1-2
- Parallel&Distributed Algorithm-2
- 【最长上升子序列LIS】O(n^2)和O(nlogn)算法简记
- 饭卡
- leetcode:Search Insert Position
- C语言的自动关机程序和一个用来整人的小程序
- pjsip例子
- 2-SUM algorithm
- 强大的vim配置文件
- CentOS7.0下安装ftp服务器的过程
- struts2+hibernate3.2+spring2.0整合篇(一)
- 学习HTMl5 开始
- 使用Spring进行事物管理
- 『ANDROID』Android SDK 国内镜像
- hdu5125 dp+树状数组
- Material Design(原质化设计)视觉设计语言规范 踏得网镜像