[LeetCode]Two Sum
2013-10-08 13:36
281 查看
Two Sum
这题思路很简单,创建一个hash table,用来存放访问过的数值和对应的位置。从头到尾循环,假如hash table里面有匹配的数值,则取出对应的数值的位置并直接返回。
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=9Output: index1=1, index2=2
这题思路很简单,创建一个hash table,用来存放访问过的数值和对应的位置。从头到尾循环,假如hash table里面有匹配的数值,则取出对应的数值的位置并直接返回。
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=9Output: index1=1, index2=2
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. map<int, int> table; map<int, int>::iterator iter; vector<int> result; int comp; for (int i = 0;i < numbers.size();++i) { comp = target - numbers[i]; iter = table.find(comp); if (iter == table.end()) { table.insert(pair<int, int>(numbers[i], i)); } else { result.push_back(iter->second + 1); result.push_back(i + 1); return result; } } return result; } };
相关文章推荐
- leetCode: two Sum
- leetcode: 1 Two Sum
- LeetCode学习_Two Sum
- 【Shawn-LeetCode】Two Sum
- [LeetCode]1. Two Sum
- leetcode Two Sum
- LeetCode(62)-Two Sum
- leetcode 1 two sum 刷题学习笔记
- leetcode:Two Sum
- LeetCode刷题笔记 01 Two Sum
- [leetcode]Two Sum
- [Leetcode] 1. Two Sum
- leetcode 1 Two Sum
- LeetCode—— Two Sum
- 【leetcode】 Two Sum
- [LeetCode]Two Sum
- LeetCode-问题1-Two Sum
- 【python】【leetcode】【算法题目1—Two Sum】
- LeetCode 1. Two Sum
- [LeetCode113]Two Sum