leetcode Two Sum 哈希表

原创 2015年07月06日 19:12:27

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

Hide Tags
 Array Hash Table

刚开始直接两层for循环超时,哈哈,还是要用哈希表。

class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {
		vector<int>res;
		if (!nums.size()) return res;
		map<int, int>Hash;
		for (int i = 0; i < nums.size(); i++)
		{
			if (Hash.find(target - nums[i]) != Hash.end())
			{
				res.push_back(Hash[target - nums[i]]+1);
				res.push_back(i+1);
				return res;
			}	
			Hash[nums[i]] = i;
		}
		return res;
	}
};


相关文章推荐

[LeetCode - 哈希表] 1. Two Sum

1 问题 Given an array of integers, return indices of the two numbers such that they add up to a spec...

Two Sum leetcode c++

  • 2015年10月01日 10:47
  • 763B
  • 下载

leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)

c++刷leetcode,有题目和算法代码,可直接在leetcode提交通过。

《LeetBook》LeetCode题解(1) : Two Sum[E]——哈希Map的应用

leetcode笔记 1.Two Sum[E] Given an array of integers, return indices of the two numbers such that they...

【高效算法设计-中途相遇法】4 Values whose Sum is 0 哈希表

4 Values whose Sum is 0 Time Limit: 15000MS   Memory Limit: 228000K Total Submission...

HDU 1258 Sum It Up(哈希表判重)

判重哈希表解决: #include using namespace std; const int nMax = 15; const int INF = 10007; int t, n; int...

LeetCode - Two Sum

Question: Given an array of integers, return indices of the two numbers such that they add up to a...

LeetCode Two sum

LeetCode Two Sum

[LeetCode]1. Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific ta...

【LeetCode】.1.Two Sum

1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode Two Sum 哈希表
举报原因:
原因补充:

(最多只允许输入30个字)