Given an array of integers that's already sorted in ascending order, find, numbers such, 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
This is a two-sum derivative problem, as the Leetcode mountain problem, we must be two sum and all of the derivative problems are taken down, this problem should be more easily, because the given array is ordered, and the topic is bound to have a solution, I began to think of the method is the dichotomy to search , because there must be a solution, and the array is ordered, then the first number must be smaller than the target value of the goal, then we use the dichotomy to search target-numbers[i], the code is as follows:
Solution One:
//O (NLGN)classSolution { Public: Vector<int> Twosum (vector<int>& numbers,inttarget) { for(inti =0; I < numbers.size (); ++i) {intt = target-numbers[i], left = i +1, right = Numbers.size ()-1; while(Left <Right ) { intMid = left + (right-left)/2; if(Numbers[mid] = = t)return{i +1, Mid +1}; Else if(Numbers[mid] < T) left = mid +1; Elseright =mid; } } return {}; }};
But the above method is not efficient, the time complexity is O (NLGN), and we look at an O (n) solution, we only need two pointers, one point to the beginning, a point to the end, and then to the middle, if the two number of points to add exactly equal to the target words, Directly return the position of two pointers, if less than target, the left pointer to the right one bit, if greater than target, the right pointer to the left one bit, and so on until the two pointer meet stop, see the code as follows:
Solution Two:
//O (n)classSolution { Public: Vector<int> Twosum (vector<int>& numbers,inttarget) { intL =0, r = numbers.size ()-1; while(L <r) {intsum = numbers[l] +Numbers[r]; if(sum = = target)return{L +1, R +1}; Else if(Sum < target) + +l; Else--R; } return {}; }};
Similar topics:
The Sum iii-data structure design
The Sum of
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Two Sum ii-input array is sorted two sum of second-input array ordered