Leetcode-search in rotated Sorted array-rotation array Search-two points search + algebraic logic

Source: Internet
Author: User

https://oj.leetcode.com/problems/search-in-rotated-sorted-array/

A rotated array that requires a binary search query for a number. Modified binary search can be done. Note that a[l]<a[r] can be used to determine the l,r median distribution of numbers. In A[l]>a[r], there is a discontinuity in the middle. The position relationship between the midpoint and the center of rotation can be judged by a[mid]>a[r]. Then move L or R through a logical comparison. Draw a line chart to understand better.

Note that the binary search termination condition is l<r, and the l=mid+1 is always used when updating the L position. This avoids the cycle of death. Determines whether a query is queried after exiting the loop by judging A[l] and the target relationship.

classSolution { Public:    intSearchintA[],intNinttarget) {        intL=0; intr=n-1; intx=Target;  while(r>l) {            intMid= (L+R)/2; if(X==a[mid])returnmid; if(a[l]<A[r]) {                if(X<a[mid]) r=mid; ElseL=mid+1; }            Else{//Al>ar                if(a[mid]<A[r]) {                    if(X<a[mid]) r=mid; Else {                        if(X>a[r]) r=mid; ElseL=mid+1; }                }                Else {                    if(X>a[mid]) l=mid+1; Else {                        if(X>a[r]) r=mid; ElseL=mid+1; }                }            }        }        if(a[l]==x)returnl; return-1; }};

Leetcode-search in rotated Sorted array-rotation array Search-two points search + algebraic logic

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.