It is assumed that an array sorted in ascending order is rotated at a predetermined point in the unknown.
(for example, the array [0,1,2,4,5,6,7]
may become [4,5,6,7,0,1,2]
).
Searches for a given target value, returns its index if the target value exists in the array, otherwise returns -1
.
You can assume that there are no duplicate elements in the array.
Your algorithm's time complexity must be O(log n) level.
Example 1:
Input: Nums = [ 4,5,6,7,0,1,2]
, target = 0 Output: 4
Example 2:
Input: Nums = [ 4,5,6,7,0,1,2]
, target = 3 output:-1
Another binary search for the upgraded version, where I use recursion, if the range is normal ascending, then normal binary lookup, if the range is a rotation sort, then the two sides are searched, if the number on the left is larger than target and the number on the right and target small, then the target is not in the range, return.
The other solution is the fastest use of iterative to do, a simple look at the next, divided into three kinds of situations, later to see the space.
voidBinsearch (int*nums,intLintRintTargetint*index) { if(l>R)return; if(nums[l]<Nums[r]) { if(nums[l]>target| | nums[r]<target)return; intMid= (L+R)/2; if(nums[mid]==target) { *index=mid; return; } Else if(nums[mid]<target) binsearch (Nums,mid+1, R,target,index); ElseBinsearch (Nums,l,mid-1, Target,index); } Else { if(nums[r]<target&&nums[l]>target)return; intMid= (L+R)/2; if(nums[mid]==target) { *index=mid; return; } Else{binsearch (Nums,mid+1, R,target,index); Binsearch (Nums,l,mid-1, Target,index); } }}intSearchint* Nums,intNumssize,inttarget) { intindex=-1; Binsearch (Nums,0, numssize-1,target,&index); returnindex;}
Search for rotated sorted arrays