Original title: https://leetcode.com/problems/two-sum/
Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Train of thought: queue, Flag,hash
The subject can be divided into two pieces:
- How to find two numbers satisfying the condition;
- How to output both of them index.
Note that the subject must have a solution, and there is only one solution, which greatly simplifies the idea.
For 1, the calculation of the complexity O (n) method is, first sort, and then the team head of the tail has a flag, when its and greater than target, the description of the big, the tail flag to move forward, and less than the target, the description is small, the team head flag back to the case, so that the two numbers found.
For 2, it is obvious to remember the index of each number, the method is to use the hash function, map to achieve.
Special cases:
There are two or more identical numbers in the queue. If the number of the same number is greater than 2, the description is not to find the number, otherwise violate the uniqueness of the principle, so do not tube; If the number is exactly two the same, there will be a hash conflict, I used a stupid method, made two map ...
Own a past code:
1#include <map>2#include <algorithom>3 classSolution {4 Public:5 6vector<int> Twosum (vector<int>& Nums,inttarget) {7vector<int>result;8Map <int,int>name,name2;9vector<int>:: iterator it,it2;Ten for(It=nums.begin (); It!=nums.end (); + +it) { One if(Name.find (*it) = =name.end ()) AName[*it]=it-nums.begin () +1; - Else -Name2[*it]=it-nums.begin () +1; the } - sort (Nums.begin (), Nums.end ()); -it=Nums.begin (); -It2=nums.end ()-1; + while(it!=it2) { - if(*it+*it2>target) +it2--; A Else if(*it+*it2<target) atit++; - Else if(*it+*it2==target) { - if(*it!=*it2) { -Result.push_back (min (name[*it],name[*it2])); -Result.push_back (Max (name[*it],name[*it2])); - } in Else{ -Result.push_back (min (name[*it],name2[*it])); toResult.push_back (Max (name[*it],name2[*it])); + } - returnresult; the } * } $ }Panax Notoginseng};
Leetcode (1)--two Sum