2-SUM algorithm

本文介绍了一个2-SUM问题的求解方法,通过读取包含1百万个整数的文件,寻找所有在[-10000,10000]区间内满足x+y=t的不同整数对(x,y)的数量。使用了C++中的set数据结构来存储输入数据,并通过双指针技术检查是否存在这样的整数对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

这个不知道怎么用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值