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
class Solution { public: vector<int> twoSum(vector<int> &numbers , int target) { vector<int> index; for(int i=0 ; i!=numbers.size(); i++) { for(int j=numbers.size()-1 ; j>i; j--) if((numbers[i]+numbers[j]) == target) { index.push_back(i+1); index.push_back(j+1); break; } }//for return index; }//twoSum };没错,想嘛,堂堂LeetCode中等难度的题目,就这样可以AC的话岂不是。。。于是,我就得到了这样的回应:
class Solution { public: vector<int> twoSum(vector<int> &numbers , int target) { vector<int> index; map<int , int> hashMap; for(unsigned int i=0 ; i<numbers.size(); i++) { if(!hashMap.count(numbers[i])) hashMap.insert(make_pair(numbers[i] , i)); if(hashMap.count(target-numbers[i])) { int pos = hashMap[target-numbers[i]]; if(pos < i) { index.push_back(pos+1); index.push_back(i+1); } }//if }//for return index; }//twoSum };这样,算法复杂度就降到了O(n),顺利AC了我的第一个LeetCode题目。
int main() { Solution s; int arr[3] = {3,2,4}; int target = 6; vector<int> numbers(arr , arr+3); vector<int> index; index = s.twoSum(numbers , target); cout<<"index1="<<index[0]<<", index2="<<index[1]<<endl; return 0; }
原文地址:http://blog.csdn.net/fly_yr/article/details/45226533