码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode之数组中找两数和为指定值

时间:2014-12-25 23:41:10      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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


思路:

最直接的思路当然是两两尝试,但是这样的时间复杂度为O(n2),这样的时间复杂度不到万不得已还是不要接受,再尝试思考,如果能用target减去数组中的一个数然后得到结果再到数组中搜寻,如果能找到即可,这样的话无疑就需要一个能搜索的数据结构了,想到map,先遍历一遍简历搜索库,然后再按照以上思路进行,这样的时间复杂度为O(n),代价是以空间换时间,这样是不是最优解呢?以后再慢慢思考吧,反正我的这段代码是通过了leetcode OJ的。
代码:

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        std::map<int, int> finder;
		for (int i = 0; i<numbers.size(); i++)
		{
			int val = numbers.at(i);
			finder.insert(std::pair<int, int>(val, i));
		}
		for (int i = 0; i<numbers.size(); i++)
		{
			int left = target - numbers.at(i);
			if (finder.find(left) == finder.end())//not found
			{
				continue;
			}
			else
			{
				std::vector<int> re;
				if(finder[left]==i)
				{
				    continue;
				}
				else if (finder[left]<i)
				{
					re.push_back(finder[left]+1);
					re.push_back(i+1);
				}
				else
				{
					re.push_back(i+1);
					re.push_back(finder[left]+1);
				}
				return re;
			}
		}
       
    }
};


leetcode之数组中找两数和为指定值

标签:

原文地址:http://blog.csdn.net/xunileida/article/details/42155461

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