"Leetcode 167", Sum ii-input array is sorted

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.