Question:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum shocould 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 wowould have exactly one solution.
Input: numbers = {2, 7, 11, 15}, target = 9
Output: index1 = 1, index2 = 2
Question analysis:
Given is an unordered vector integer array and a target, the sorted array in the question is only a special case.
It is required to find two numbers in the array, whose sum is equal to the target, and that such numbers have only one pair. Therefore, we do not consider the case where such numbers cannot be found here.
You can also consider the combination of vector and multimap.
Nlogn is consumed for sorting, n is consumed for searching, n is consumed for two subscripts, and the total time complexity is nlogn.
- First, back up the original array to store the original location of each number.
- Sort the array, and move the two ends closer to the middle until the required integer pair is found.
- Search for the positions of the two integers in the backup array and save them to the returned results.
Code:
# Include <iostream> # include <vector> # include <map> # include <algorithm> using namespace std; class Solution {public: vector <int> twoSum (vector <int> & numbers, int target) {int vecSize = numbers. size (); int nStart = 0; // start position of the search int nTail = vecSize-1; vector <int> findLoc (numbers ); // to save the original array sequence vector <int> VerRes; // Save the returned subscript result sort (numbers. begin (), numbers. end (); // sort data first, and perform a while (nStart <= nTail) {if (numbe Rs [nStart] + numbers [nTail] <target) {nStart ++;} else if (numbers [nStart] + numbers [nTail]> target) {nTail --;} else if (numbers [nStart] + numbers [nTail] = target) // records the position of the result data pair in the original vector {for (int I = 0; I <vecSize; I ++) {if (numbers [nStart] = findLoc [I]) // find the subscript {VerRes. push_back (I + 1); break ;}} for (int I = 0; I <vecSize; I ++) {if (numbers [nTail] = findLoc [I] & (I + 1 )! = VerRes [0]) {VerRes. push_back (I + 1); break ;}} sort (VerRes. begin (), VerRes. end (); return VerRes ;}}; int main () {vector <int> num; vector <int> res; num. push_back (0); num. push_back (2); num. push_back (4); num. push_back (0); int target = 0; res = Solution (). twoSum (num, target); for (int I = 0; I <res. size (); I ++) {cout <res [I] <"" ;}cout <endl; system ("pause ");}
Two Sum of LeetCode