Problem Description:
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
struct node{ int val; int indexs; }; bool compare(node a,node b) { return a.val<b.val; } class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; if(numbers.size()<2) return res; vector<node> nums; for(vector<int>::size_type index=0;index!=numbers.size();++index) { node temp; temp.val=numbers[index]; temp.indexs=index+1; nums.push_back(temp); } sort(nums.begin(),nums.end(),compare); vector<node>::iterator p=nums.begin(); vector<node>::iterator q=nums.end()-1; while(p<q) { if((p->val+q->val)>target) q--; else if((p->val+q->val)<target) p++; else { if(p->indexs<q->indexs) { res.push_back(p->indexs); res.push_back(q->indexs); } else { res.push_back(q->indexs); res.push_back(p->indexs); } break; } } return res; } };
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; if(numbers.size()<2) return res; unordered_map<int,int> numsmap; for(vector<int>::size_type index=0;index!=numbers.size();++index) numsmap[numbers[index]]=index; unordered_map<int,int>::iterator flag=numsmap.end(); for(vector<int>::size_type index=0;index!=numbers.size();++index) { int temp=target-numbers[index]; flag=numsmap.find(temp); if(flag!=numsmap.end()&&flag->second!=index) { if(index<flag->second) { res.push_back(index+1); res.push_back(flag->second+1); } else { res.push_back(flag->second+1); res.push_back(index+1); } break; } } return res; } };
Leetcode--Two Sum,布布扣,bubuko.com
原文:http://blog.csdn.net/longhopefor/article/details/38322565