假設按照升序排序的數組在預先未知的某個點上進行了旋轉。算法
( 例如,數組 [0,1,2,4,5,6,7] 可能變爲 [4,5,6,7,0,1,2] )。數組
搜索一個給定的目標值,若是數組中存在這個目標值,則返回它的索引,不然返回 -1 。spa
你能夠假設數組中不存在重複的元素。code
你的算法時間複雜度必須是 O(log n) 級別。blog
示例 1:排序
輸入: nums = [4,5,6,7,0,1,2], target = 0
輸出: 4索引
示例 2:get
輸入: nums = [4,5,6,7,0,1,2], target = 3
輸出: -1io
在 $a[0 \sim (size-1)]$ 中查找 $x$:class
首先考慮一個狀況,數組是空的,那麼直接返回 $-1$;
其次,考慮沒有進行旋轉的狀況,這個能夠根據 $a[0]<a[size-1]$ 判斷,這樣的話直接用lower_bound找第一個不小於 $x$ 的位置,這樣就能夠判斷數組 $a$ 中是否存在 $x$;
再次,先用二分找到旋轉數組的分界點,而後對兩段分別lower_bound查找 $x$。
AC代碼:
int Srch(const vector<int>& a,int st,int ed,int x) { int l=st, r=ed; while(l<r) { int mid=(l+r)/2; if(a[mid]<x) l=mid+1; else r=mid; } if(a[l]!=x) return -1; else return l; } class Solution { public: int search(const vector<int>& a,int x) { if(a.empty()) return -1; if(a.front()<a.back()) return Srch(a,0,a.size()-1,x); int l=0, r=a.size()-1; while(r-l>1) { int mid=(l+r)/2; if(a[mid]>a.front()) l=mid; else if(a[mid]<a.back()) r=mid; } return max(Srch(a,0,l,x),Srch(a,r,a.size()-1,x)); } };