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