Suppose a sorted array is rotated at some pivot unkonwn to you beforehand. (i.e.,0,1,2,4,5,6,7 might become 4 5 6 7 0 1 2).ios
You are given a target values to search.If found in the array return its index,otherwise return -1.You may assume no duplicate exists in the array.數組
這個題目是用二分法在旋轉數組中查找目標值。 旋轉數組旋轉後,原來總體有序的數組如今變成了分段有序。旋轉軸左邊的數組是有序的,旋轉軸右邊的一樣是有序的,而且均是單調遞增。 不過再使用二分法查找,可能會有些不一樣。旋轉軸可能不在mid的位置上,因此可能first~mid這段或者是mid~last這段並非遞增有序的。測試
可是,若是知足a[mid]>=a[1],則在1~mid這段的元素就是遞增的;spa
知足a[mid]< a[last],則在mid~last這段就是遞增的。code
解決方案:get
class Solution { public: int search(const vector<int> &num,int target) { int first = 0; int last = num.size(); while(first != last) { const int mid = first + (last - first)/2; if(num[mid] == target) return mid; if(num[first]<= num[mid]) { if(num[first] <= target && num[mid] > target) { last = mid; } else { first = mid + 1; } } else { if(num[mid] < target && num[last-1] >= target) { first = mid + 1; } else { last = mid; } } } return -1; } };
測試代碼:it
#include<iostream> #include<vector> using namespace std; class Solution { public: int search(const vector<int>& num,int target) { int first = 0; int last = num.size(); while(first != last) { const int mid = first + (last - first)/2; if(num[mid] == target) return mid; if(num[first] <= num[mid]) { if(num[first] <= target && num[mid] > target) last = mid; else first = mid + 1; } else { if(num[mid]<= target && num[last] > target) first = mid + 1; else last = mid; } } return -1; } }; int main(void) { vector<int> a; int target = 1; a.push_back(4); a.push_back(5); a.push_back(6); a.push_back(7); a.push_back(1); a.push_back(2); a.push_back(3); Solution s; int result = s.search(a,target); cout <<"The"<<target<<"is located in "<<result<<endl; return 0; }