problem Description: give an array of integers in ascending order, find 2 numbers, and they are equal to the number of targets. Returns the subscript for these two numbers (starting from 1), where the 1th subscript is smaller than the 2nd subscript.
Input:numbers={2, 7, one, A, target=9
Output:index1=1, index2=2
Analysis: in a sorted array to find, it is easy to think of the idea of two-point search. Here quite then the two points find two numbers, and the minimum and maximum values can be summed as the starting point (sum).
If sum<target, it is necessary to make the smaller element, also the low element larger, at this time can not directly assign the mid value to low, because if NUMBERS[MID] + Numbers[high] > target, then there may be two number one in , mid) region a case in the [Mid, high] region, i.e. a number less than Numbers[mid] x satisfies the X + numbers[high] = = target, at which point the low is directly placed in a grid.
The same is true of Sum>target.
Solution:
vector<int> Twosum (vector<int>& numbers,inttarget) { intLow =0; intHigh = Numbers.size ()-1; while(Low <High ) { intMid = (low + high) >>1; Long Sum= Numbers[low] +Numbers[high]; if(Sum = =target)returnvector<int>{low +1, High +1}; Else if(Sum >target) high= (Numbers[low] + Numbers[mid] > target)? Mid:high-1; Else Low= (Numbers[mid] + Numbers[high] <= target)? Mid:low +1; } returnvector<int>(); }
The extreme situation is that each time you cannot move to a two-point position, you can only enter 1 or abdication, that is, O (n).
But it's hard to cite an example of this extreme situation and suddenly intuitively feel as if it's hard to reach the complexity of O (n) ... It seems to be O (logn) ... Math is not very good, prove, and then go to the discussion area to see it
"Leetcode 167", Sum ii-input array is sorted