码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum

时间:2015-05-20 22:22:28      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:c++   刷题   

Given an array of integers, find two numbers such that they add up to a specific target number.The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

题目翻译:这道题目的意思是给定一个数组和一个值,让求出这个数组中两个值的和等于这个给定值的坐标。输出是有要求的:坐标较小的放在前面,较大的放在后面,这俩坐标不能为零。

这里用hash_map来解决,把每个数都存入map中,任何再逐个遍历,查找是否有 target – nubmers[i]。 时间复杂度 O(n)。

vector<int> twoSum(vector<int>& nums, int target) 
{
	vector<int> ret;
	if (nums.size()<=1)
	{
		return ret;
	}
	//新建一个map<key,value>,用来存储nums里面的元素和index
	map<int,int> myMap;
	for (int i=0; i<nums.size(); i++)
	{
		myMap[nums[i]]=i;
	}
	for (int i=0; i<nums.size(); i++)
	{
		int resValue=target-nums[i];
		//如果找到resValue
		if (myMap.find(resValue)!=myMap.end())
		{
			int index=myMap[resValue];
			if (index>i)
			{
				ret.push_back(i+1);
				ret.push_back(index+1);
				return ret;
			}
		}
	}
}


Two Sum

标签:c++   刷题   

原文地址:http://blog.csdn.net/lsh_2013/article/details/45875609

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!