标签:
对翻过一次的排序数组二分查找,要利用好已排序这个条件
class Solution { public: int search(int A[], int n, int target) { int left = 0, right = n-1; while(left <= right){ int mid = (left+right)/2; if(A[mid] == target) return mid; if(A[left] <= A[mid]){ if(A[left] <= target && target < A[mid]) right = mid-1; else left = mid+1; } else { if(A[mid] < target && target <= A[right]) left = mid+1; else right = mid-1; } } return -1; } };
class Solution { public: bool search(int A[], int n, int target) { int left = 0, right = n-1; while(left <= right){ int mid = (left+right)/2; if(A[mid] == target) return true; if(A[left] < A[mid]){ if(A[left] <= target && target < A[mid]) right = mid-1; else left = mid+1; } else if(A[left] > A[mid]){ if(A[mid] < target && target <= A[right]) left = mid+1; else right = mid-1; } else left++; } return false; } };
Search in Rotated Sorted Array I && II
标签:
原文地址:http://blog.csdn.net/sina012345/article/details/43232267