标签:leetcode
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.
class Solution { public: int search(int A[], int n, int target) { int left = 0; int right = n-1; while(left <= right)//left,right均为 mid +/- 1,存在交错,满足退出条件 { int mid = (left+right)/2; if(target == A[mid]) return mid; if(A[left] <= A[mid])//mid 在左侧 较大的区间 { if((A[left] <= target)&&(target < A[mid])) //target != A[mid] 上式以排除。target在左侧递增区间 right = mid - 1; //target != A[mid],可以让right = mid -1 else//化为原型式 left = mid + 1;// 用mid+1, 存在 left<=mid, target != A[mid],所以可用left = mid + 1 } else {//mid在右侧区间 if((A[mid] < target)&&(target <= A[right])) left = mid + 1; else//化为原型式 right = mid - 1; } } return -1; } };
Search in Rotated Sorted Array--leetcode
标签:leetcode
原文地址:http://blog.csdn.net/youxin2012/article/details/41576717