title :
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.
Code :
classSolution { Public: intSearchintA[],intNinttarget) { intBegin =0; intEnd = N1; while(Begin! =end) { if(begin+1==end) { if(A[begin]==target)returnbegin; if(A[end]==target)returnend; return-1; } Const intMid = (end+begin)/2; if(A[mid]==target)returnmid; if(target<A[mid]) { if(a[begin]<A[mid]) { if(target>=A[begin]) {End= mid-1; } Else{begin= mid+1; } } Else{End= mid-1; } } Else { if(a[begin]<A[mid]) {Begin= mid+1; } Else { if(target<=A[end]) {Begin= mid+1; } Else{End= mid-1; } } } } if(A[begin]==target)returnbegin; return-1; }};
Tips:
1. The size of target and A[mid] is discussed first
2. Because at least one of the first half or the second half is orderly, and then according to this to sub-condition discussion
There are some logic in the if else code that can be combined, but keeping the original logic in mind is easier to understand, preserving the status quo.
"Search in rotated Sorted Array" cpp