"Leetcode" Search in rotated Sorted Array (hard)

Source: Internet
Author: User

Suppose a sorted array is rotated on some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).

You is given a target value to search. If found in the array is return its index, otherwise return-1.

Assume no duplicate exists in the array.

Idea: Two-point search, remove half of the error options at a time.

Note that every time L = m + 1, r = m-1 prevents infinite loops.

intSearchintA[],intNinttarget) {    intL =0, R = N-1;  while(L <=r)//note that there is an equal sign {intm = (L + r)/2; if(A[m] = =target)returnm; if(A[l] <= a[m] && a[m] <= A[r])//Order of        {            if(A[m] >target) R= M-1; ElseL= m +1; }        Else if(A[l] >= a[m] && a[m] <= A[r])//the beginning goes to the left half.        {            if(A[m] < target && target <= A[r])//in the right-hand partL = m +1; ElseR= M-1; }        Else //the beginning goes to the right half.        {            if(A[l] <= target && target <= a[m])//in the left half partr = M-1; ElseL= m +1; }    }    return-1;}

Great God simplified version: the idea of removing half of the options is different

intSearchintA[],intNinttarget) {    intLo =0; intHi = N-1;  while(Lo <=hi) {        intMid = (lo + hi)/2; if(A[mid] = = target)returnmid; if(A[lo] <=A[mid]) {            if(Target >= A[lo] && Target <A[mid]) {Hi= Mid-1; } Else{lo= Mid +1; }        } Else {            if(Target > A[mid] && target <=A[hi]) {Lo= Mid +1; } Else{Hi= Mid-1; }        }    }    return-1;}

"Leetcode" Search in rotated Sorted Array (hard)

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.