题目链接
https://leetcode.com/problems/search-in-rotated-sorted-array/description/
题目描述
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
题解
根据题目要求的时间复杂度,这题需要使用二分查找。每次二分查找之后,我们找到该数组中单调的部分来和目标元素相比较。这样可以避免漏掉一些情况。
代码
class Solution {
public int search(int[] a, int target) {
if (a == null || a.length == 0) {
return -1;
}
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int mid = (lo + hi) >> 1;
if (a[mid] == target) { return mid; }
if (a[mid] > a[hi]) {
if (a[lo] <= target && target < a[mid]) {
hi = mid - 1;
} else {
lo = mid + 1;
}
} else {
if (target > a[mid] && target <= a[hi]) {
lo = mid + 1;
}else {
hi = mid - 1;
}
}
}
return -1;
}
}