思路一:顺序查找即可
思路二:二分查找。
class Solution {
public:
bool search(int A[], int n, int target) {
if(A == nullptr || n <= 0)
return false;
int left = 0, right = n - 1;
while(left <= right){
int mid = left + ((right - left) >>1);
if(A[mid] == target)
return true;
if(A[mid] > A[left]){//left-mid是升序序列
if(target >= A[left] && target < A[mid])//target在left-mid
right = mid - 1;
else
left = mid + 1;
}
else if(A[mid] < A[left]) {//left-mid不是升序
if(target > A[mid] && target <= A[right])//在mid-right之间
left = mid + 1;
else
right = mid - 1;
}
else
left++;///!!!!!注意A[mid]等于A[left]的时候不能排除哪一半数字了,只能left++!!!
}
return false;
}
};