一、题目
力扣原题:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/
二、暴力
- 时间复杂度:O(n)
- 空间复杂度:O(1)
三、二分查找
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target == nums[mid]) {
return mid;
}
// 左边有序
if (nums[mid] >= nums[0]) {
if (target < nums[mid] && target >= nums[0]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// 右边有序
else {
if (target > nums[mid] && target <= nums[nums.length - 1]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
}
- 基本思路:二分查找的变种,关键在于判断以mid分割,左边有序还是右边有序
- 时间复杂度:O(log(n))
- 空间复杂度:O(1)
四、总结
- 有序数组的查找应该尽量采用二分查找