【LeetCode-33】33. 搜索旋转排序数组
程序员文章站
2022-07-02 11:04:22
...
搜索旋转排序数组
修改的二分查找
注意:这道题的数组中没有重复数字
class Solution {
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return -1;
}
int n = nums.length;
if(n == 1) {
return nums[0] == target ? 0 : -1;
}
int left = 0;
int right = n - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(nums[mid] == target) {
return mid;
}
//注意找出左/右中哪一部分有序
//1.left-mid是有序的
if(nums[0] <= nums[mid]) {
if(nums[0] <= target && target < nums[mid]) {
//左边界有序且target在有序的左半边
right = mid - 1;
} else {
left = mid + 1;
}
} else if(nums[0] > nums[mid]){
//2. mid-right是有序的
//target在有序的序列中
if(nums[mid] < target && target <= nums[n - 1]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
}
class Solution {
public int search(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
int mid;
while (start <= end) {
mid = start + (end - start) / 2;
if (nums[mid] == target) {
return mid;
}
//前半部分有序,注意此处用小于等于
if (nums[start] <= nums[mid]) {
//target在前半部分
if (target >= nums[start] && target < nums[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (target <= nums[end] && target > nums[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return -1;
}
}
同类型题目
注意该题的数组包含重复元素
81.搜索旋转排序数组 II