题目描述
思路:是lc33.搜索旋转排序数组的延伸,允许包含重复元素
起初:
- 当nums[left] <= nums[mid]时,区间[left,mid]有序
- 当nums[left] > nums[mid]时,区间[mid ,right]有序
但是这个题目当nums[left] == nums[mid]时,无法判断哪个区间是有序的,无法判断target位于左侧还是右侧,此时无法缩小区间,退化为顺序查找,即在[left,right]区间上直接遍历每一项。
方法一:
class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length == 0) return false;
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (target == nums[mid]) return true;
if (nums[left] < nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else if (nums[left] == nums[mid]) {
for (int i = left; i <= right; i ++) {
if (target == nums[i]) return true;
}
// 如果顺序查找都没找到,说明不存在这个元素
return false;
} else if (nums[left] > nums[mid]){
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return false;
}
}
标签:right,target,nums,int,mid,LeetCode81,II,LeetCode,left
From: https://www.cnblogs.com/keyongkang/p/17916278.html