"Leetcode" Search in rotated Sorted Array

Source: Internet
Author: User

Search in rotated Sorted Array

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.

Using the dichotomy, if LEFT<A[MID], the description from left to right start to mid is ordered if LEFT>A[MID], the description of the rights start from mid, and to that is ordered if LEFT=A[MID], Then the left and mid are in the same position, if A[mid]!=target is the next left=left+1;
1 classSolution {2  Public:3     intSearchintA[],intNinttarget) {4        5         intleft=0;6         intright=n-1;7         intmid;8          while(left<=Right )9         {TenMid= (left+right)/2; One             A             if(A[mid]==target)returnmid; -             -             if(A[left]<a[mid])// Left the             { -                 if(a[left]<=target&&target<A[mid]) -                 { -right=mid-1; +                 } -                 Else +                 { ALeft=mid+1; at                 } -             } -             Else if(A[left]>a[mid])// Right -             { -                 if(a[mid]<target&&target<=A[right]) -                 { inLeft=mid+1; -                 } to                 Else +                 { -right=mid-1; the                 } *             } $             ElsePanax Notoginseng             { -                 //The Last Judgment statement can be put together in the first statement, if (A[left]<=a[mid]) theLeft=mid+1; +             } A             the         } +         return-1; -     } $};

"Leetcode" Search in rotated Sorted Array

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.