Topic:
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 less 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
Test instructions
The topic asks for an array of shapes and a target to find the two elements in the integer array so that the sum of the two elements equals the value of the specified target. The topic assumes that the two elements must exist, and that there is only one set (so relatively simple), which returns the index value of the two elements (the array index starts at 1).
Keng:
We get this topic, the first thing we can think of is two traversal, but this time complexity is O (n^2), can not pass the Leetcode OJ test. So we need to find another way. Must be less than O (n^2) complexity.
Key point:
We often use space in exchange for time to get a small amount of time complexity. Therefore, the necessary data structures are added to reduce the complexity of time. As with this topic, we add a map structure, the key is an array element value, and value is the index of its corresponding in the arrays. Each time the array element is traversed to find the corresponding complement in the map structure, if it exists, then it is found. If it does not exist, record the current element and its index until the end.
Answer:
1 classsolution{2 Public:3 //o (n) runtime, O (n) space4 //We could reduce the runtime complexity of looking up a value to O (1) using a hash map, maps a value to its index. 5std::vector<int> Twosum (std::vector<int>& numbers,inttarget) {6std::vector<int>Vecret;7std::map<int,int>Mapindex;8 for(size_t i =0; I < numbers.size (); ++i) {9 if(0! = Mapindex.count (Target-Numbers[i])) {Ten intNIndex = Mapindex[target-Numbers[i]]; One //the current stored index must be smaller than I, note to exclude I A if(NIndex <i) { -Vecret.push_back (NIndex +1); -Vecret.push_back (i +1); the returnVecret; - } -}Else { -Mapindex[numbers[i]] =i; + } - } + returnVecret; A } // Twosum
*};
Operation Result:
I hope you crossing, little brother grateful words Xie ~
[Leetcode] [012] and Sum (1)