标签:c++ leetcode binary search array
Search in Rotated Sorted Array
Suppose a sorted array is rotated at 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 are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
//vs2012测试代码 #include<iostream> using namespace std; #define N 5 //observation is the key, try to solve it by modifying binary search class Solution { public: int search(int A[], int n, int target) { if( n==0 ) return -1; int mid = 0; int left=0, right=n-1; while( left <= right) { mid = left + (right-left)/2 ; if(A[mid] == target) return mid; if( A[left] <= A[mid] ) //left side sorted, including mid, it is sorted in [l,mid] { if( A[mid] > target && A[left] <= target ) right = mid - 1; else left = mid + 1; } else if ( A[left] > A[mid] ) //right side sorted, [mid,r] must be sorted, if [l,mid] not sorted { if ( A[mid] < target && A[right] >= target ) left = mid + 1; else right = mid - 1; } } return -1; } }; int main() { int a , target; int A[N]; for(int i=0; i<N; i++) { cin>>a; A[i] = a; } cin>>target; Solution lin; cout<<lin.search( A,N,target)<<endl; }
//方法一:自测Accepted //observation is the key, try to solve it by modifying binary search class Solution { public: int search(int A[], int n, int target) { if( n==0 ) return -1; int mid = 0; int left=0, right=n-1; while( left <= right) { mid = left + (right-left)/2 ; if(A[mid] == target) return mid; if( A[left] <= A[mid] ) //left side sorted, including mid, it is sorted in [l,mid] { if( A[mid] > target && A[left] <= target ) right = mid - 1; else left = mid + 1; } else if ( A[left] > A[mid] ) //right side sorted, [mid,r] must be sorted, if [l,mid] not sorted { if ( A[mid] < target && A[right] >= target ) left = mid + 1; else right = mid - 1; } } return -1; } };
//方法二:其他版本 class Solution { public: int search(int A[], int n, int target) { int left = 0; int right = n-1; while(left < right) { int mid = left+(right-left)/2; if(A[mid] >= A[left])//left side sorted, including mid, { if(A[left] <= target && target <= A[mid]) right = mid; else left = mid+1; } else//right side sorted { if(A[mid] <= target && target <= A[right]) left = mid; else right = mid-1; } } if(right >= 0 && right < n && A[right] == target) return right; else return -1; } };
leetcode_33_Search in Rotated Sorted Array
标签:c++ leetcode binary search array
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43611775