leetcode--Two Sum
2013-08-18 22:08
513 查看
1.题目描述
1.解法分析
由于题目说得很明白,一定有解且解只有一组,那么这题用hash做自然是最快了,但是对于偶数输入,比如target为8,如果结果是4和4的相加需要特殊考虑。
[code]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 [/code] |
1.解法分析
由于题目说得很明白,一定有解且解只有一组,那么这题用hash做自然是最快了,但是对于偶数输入,比如target为8,如果结果是4和4的相加需要特殊考虑。
[code]class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { // Start typing your C/C++ solution below // DO NOT write int main() function unordered_set<int> myHash; vector<int>::iterator iter; vector<int> result; result.assign(2,0); if(target%2==0) { int count=0; for(int i=0;i<numbers.size();++i) { if(numbers[i]==target/2) { if(count==0){result[0]=i+1;count++;} else {result[1]=i+1;return result;} } } } for(iter=numbers.begin();iter!=numbers.end();++iter) { myHash.insert(*iter); } for(int i=0;i<numbers.size();++i) { myHash.erase(numbers[i]); if(myHash.count(target-numbers[i])==1) { result[0]=i+1;break; } myHash.insert(numbers[i]); } for(int i=result[0];i<numbers.size();++i) { if((numbers[result[0]-1]+numbers[i])==target) { result[1]=i+1;break; } } return result; } }; [/code] |
相关文章推荐
- LeetCode 学习笔记:Question 1、Two Sum
- 【leetcode系列】Two Sum
- LeetCode题解——Two Sum
- leetcode-two sum
- [leetcode, python] Two Sum 两数之和等于某数
- 【LeetCode】Two Sum
- Leetcode-1:Two Sum
- LeetCode 151 Two Sum
- LeetCode 1. Two Sum
- LeetCode1-Two Sum
- Leetcode-01 two sum
- leetcode - Two Sum
- leetcode 1 Two Sum
- [LeetCode]Two Sum
- LeetCode No.1 Two Sum
- LeetCode | Two Sum
- leetcode----Two Sum
- leetcode_two sum()
- [Leetcode]1. Two Sum
- leetcode1 Two Sum