LeetCode question | Two Sum
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
Ideas:
Enter an unordered array and a target sum, and find the subscript of the sum of the two numbers and the target number, which has different sizes.
Currently, we have three methods:
(1) brute force Enumeration
Traverse the entire array and test whether the difference between the target and the number is in the array. If so, the two numbers are to be searched and Their subscript is obtained.
The time complexity is O (N * N), and the reminder timeout during submission is despised.
(2) hashtable
C ++ STL does not have a hashtable template class that can be directly used. You can use hashtable implemented by other libraries or write one by yourself.
Hashtable can find an element in O (1) time complexity. Therefore, using hashtable for brute force enumeration will reduce the time complexity to O (N)
(3) Double pointer
First, sort the array. At first, a pointer points to the first element of the array, and another pointer points to the last element. If the sum of the two numbers is greater than target, the right pointer is shifted to the left. On the contrary, the left pointer is shifted to the right.
The sorting time complexity is O (N * lg N), and the search time complexity is O (N). Therefore, the overall time complexity is O (N * lg N)
Solution:
Methods 3
Class Solution {public: vector
TwoSum (vector
& Numbers, int target) {vector
Tmp (numbers. size (); // create an equal-to-Large Array vector
Res; // Save the result copy (numbers. begin (), numbers. end (), tmp. begin (); // copy sort (tmp. begin (), tmp. end (); // sort vector
: Iterator start = tmp. begin (); // left pointer vector
: Iterator terminate = tmp. end ()-1; // right pointer while (* start + * terminate )! = Target) {if (* start + * terminate)> target) terminate --; if (* start + * terminate)
: Iterator a; vector
: Iterator B; if (* start! = * Terminate) {a = find (numbers. begin (), numbers. end (), * start); B = find (numbers. begin (), numbers. end (), * terminate);} else {a = find (numbers. begin (), numbers. end (), * start); B = find (a + 1, numbers. end (), * terminate); // the start point for the second query is different} res. push_back (a-numbers.begin () + 1); res. push_back (b-numbers.begin () + 1); sort (res. begin (), res. end (); return res ;}};
Submission Result: Accepted