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

leetcode---------------Two Sum

时间:2015-01-07 23:40:44      阅读:362      评论:0      收藏:0      [点我收藏+]

标签:leetcode   遍历   索引   map   hash   

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

题目意思是:给定一个数组,给一个数target,在数组找到两个数的和为target,找出这个两个数的位置,其下标索引从1开始算起。

思路:

方法一:暴利求,两个for循环遍历,找到退出,复杂度O(n2)

方法二::hash 用一个哈希表,存储每个数对应的下标,复杂度 O(n).

方法二解答:

class Solution 
{
public:
	vector<int> twoSum(vector<int> &numbers, int target) 
	{
		unordered_map<int, int> mapping;
		vector<int> result;
		for (int i = 0; i < numbers.size(); ++i)
		{
			mapping[numbers[i]] = i;
		}
		for (int i = 0; i < numbers.size(); ++i)
		{
			const int tmp = target - numbers[i];
			if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i)
			{
				result.push_back(i+1);
				result.push_back(mapping[tmp] + 1);
				break;
			}
		}
		return result;
	}
};
 在线推送结果为:技术分享


Question: 
Similar to Question [1. Two Sum], except that the input array is already sorted in 
ascending order. 

问题:假如数组是有序的话我们就可以同时从头尾开始向中遍历。

class Solution
{
public:
	vector<int> twoSum(vector<int> &numbers, int target)
	{
		vector<int> result;
		int i = 0;
		int j = numbers.size() - 1;
		while (i < j)
		{
			int sum = numbers[i] + numbers[j];
			if (sum < target)
				++i;
			else if (sum>target)
				--j;
			else
			{
				result.push_back(i + 1);
				result.push_back(j + 1);
				break;
			}
		}
		return result;
	}
};




leetcode---------------Two Sum

标签:leetcode   遍历   索引   map   hash   

原文地址:http://blog.csdn.net/chenxun_2010/article/details/42499199

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