Searching for rotated arrays-classic

Source: Internet
Author: User

Https://leetcode.com/problems/search-in-rotated-sorted-array/?tab=Description

Very good, very classic topic. Review it today. Although there are previous ideas, the processing of equal numbers is complex and error-prone. Today, I saw a good solution.

Https://discuss.leetcode.com/topic/3538/concise-o-log-n-binary-search-solution

The idea is to find the smallest number of subscripts, through mid > Hi, on low = mid+1, otherwise hi=mid, to find out.

Then the two points are searched, with the actual subscript offset.

Overall code:

classSolution { Public:    intSearchintA[],intNinttarget) {        intlo=0, hi=n-1; //find the index of the smallest value using binary search. //Loop would terminate since mid < Hi, and lo or hi'll shrink by at least 1. //Proof by contradiction, so mid < Hi:if Mid==hi, then Lo==hi and Loop would has been terminated.         while(lo<hi) {            intMid= (Lo+hi)/2; if(A[mid]>a[hi]) lo=mid+1; ElseHi=mid; }        //Lo==hi is the index of the smallest value and also the number of places rotated.        introt=Lo; Lo=0; hi=n-1; //The usual binary search and accounting for rotation.         while(lo<=hi) {            intMid= (Lo+hi)/2; intRealmid= (Mid+rot)%N; if(A[realmid]==target)returnRealmid; if(A[realmid]<target) lo=mid+1; Elsehi=mid-1; }        return-1; }};

Of course, there is a conventional approach, and that's it.

When considering a problem, don't be too complicated.

 Public intSearchint[] A,inttarget) {    intLo =0; inthi = A.length-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; }        }    }    returnA[lo] = = target? Lo:-1;}

Searching for rotated arrays-classic

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.