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.
Ideas:
Give you a sorted but shifted array to find a specific number. Drawing a picture is easy to understand. A rotated ordered array A[1..N], assuming the turning point is a[k], then a[k+1] < a[k+2] < ... < A[n] < A[1] < A[2] < ... < a[k]
You can find a slightly pity Dorado type with two points: although we don't know where the inflection point k is, we can still compare A[mid] with a[start],a[end to determine whether the target is in A[start,..., mid] or a[mid+1,... , end] So time complexity or LG (n)
Code:
Runtime: ms
classsolution{ Public: intSearchintA[],intNinttarget) { if(N <=0) return-1; if(n = =1) return*a = = target?0: -1; intBegin =0, end = N, mid = (begin + END)/2; if(A[begin] <= a[mid-1]) { if(Target >= A[begin] && target <= a[mid-1]) {Auto it= Lower_bound (A, A +mid, Target); if(*it = =target)returnIT-A; Else return-1; } intres = search (A + Mid, end-mid, Target); returnres = =-1? -1: Mid +Res; } Else { if(Target >= A[mid] && target <= a[end-1]) {Auto it= Lower_bound (A+mid, A +end, target); if(*it = =target)returnIT-A; Else return-1; } intres = search (A + begin, Mid-begin, target); returnres = =-1? -1: Begin +Res; } }};
Leetcode problem--Search in rotated Sorted Array