标签:
也是通过二分搜索来解决,先通过一个二分搜索找到旋转的点,再分别对前后两个有序数组使用二分搜索,思路很简单,代码也没自己写了。
转:http://blog.csdn.net/zhangwei1120112119/article/details/16829309
class Solution { public: int search_2(vector<int>& A, int L, int R, int target) { while(L<=R) { int mid=(L+R)>>1; if(A[mid]>target) { R=mid-1; } else if(A[mid]<target) { L=mid+1; } else return mid; } return -1; } int search(vector<int>& nums, int target) { int n=nums.size(); vector<int> A(nums); if(n == 0) return -1; if(n == 1) { if(A[0] == target) return 0; else return -1; } if(n == 2) { if(A[0] == target) return 0; else if(A[1] == target) return 1; else return -1; } int L=0,R=n-2; while(L<R)//[0,n-2]找一个比A[n-1]大的数 { int mid=(L+R>>1)+1; if(A[mid]>A[n-1]) L=mid; else R=mid-1; } int split=L; if(A[L]<A[n-1]) split=n-1; //[0,split],[split+1,n-1] int ans; ans=search_2(A,0,split,target); if(ans!=-1) return ans; if(split+1<=n-1) { return search_2(A,split+1,n-1,target); } return -1; } };
Search in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/qiaozhoulin/p/4578622.html