0
点赞
收藏
分享

微信扫一扫

两个数之和

是归人不是过客 2022-04-04 阅读 101
c++
#include<iostream>
#include<vector>
#include<map>

using namespace std;

vector<int> getTheTwoNumsIndex(vector<int> testVec, int target)
{
	map<int, int> helperMap;//建立一个辅助map,key是数组元素的值,value是下标的值

	vector<int> resultVec(2, -1);
	for (int i = 0; i < (int)testVec.size(); i++)
	{
		int otherPartValue = target - testVec[i];
		if (helperMap.find(otherPartValue) != helperMap.end())
		{
			//说明可以找到另外一部分;
			resultVec[0] = i;
			resultVec[1] = helperMap[otherPartValue];
			return resultVec;
		}

		//找不到另一半就先放入辅助map,key是数组元素的值,value是下标的值,
		//方便之后的数字如果需要这个数字组成target的时候,通过这个map可以快速找到这个值和它对应的下标
		helperMap.insert(pair<int, int>(resultVec[i], i));
	}
	return resultVec;
}

int main()
{
	vector<int> testVec = { 2, 7, 11, 15 };
	int target = 26;

	vector<int> resultVec = { -1,-1 };
	resultVec = getTheTwoNumsIndex(testVec,target);

	cout << "the two num index is  " << resultVec[0] <<  "  and  " << resultVec[1]  << endl;
}
举报

相关推荐

0 条评论