lintcode-63-搜索旋转排序数组 II
63-搜索旋转排序数组 II
跟进“搜索旋转排序数组”,假如有重复元素又将如何?
是否会影响运行时间复杂度?
如何影响?
为何会影响?
写出一个函数判断给定的目标值是否出现在数组中。样例
给出[3,4,4,5,7,0,1,2]和target=4,返回 true
标签
数组 排序数组 二分法
思路
在搜索旋转数组的基础上 判断 left 和 mid 的值相等的情况 ,参见lintcode-62-搜索旋转排序数组
code
class Solution {
/**
* param A : an integer ratated sorted array and duplicates are allowed
* param target : an integer to be search
* return : a boolean
*/
public:
bool search(vector<int> &A, int target) {
// write your code here
int low = 0, high = A.size()-1, size = A.size(), mid = 0;
if(size <= 0 ) {
return 0;
}
while(low <= high) {
mid = low + (high - low) / 2;
if(A[mid] == target) {
return 1;
}
if(A[mid] > A[low]) {
if(A[low] <= target && target < A[mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
else if(A[mid] < A[low]){
if(A[mid] < target && target <= A[high]) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
else {
low++;
}
}
return 0;
}
};