Leetcode--Two Sum
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; } };
在discuss中看到有利用hash_map的性质来做的,实质就是利用map记录下每一个元素的下标,然后固定一个元素查找还有一个元素是否存在,时间复杂度能够达到O(n),详细实现例如以下:
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; } };