题目链接:https://leetcode.com/problems/search-in-rotated-sorted-array/
问题要求在O(logn)时间复杂度完成。
思路一:其实本题可以用最坏时间复杂度为O(n)的解法侥幸AC,而且Beat 32.69%,参考这篇博客https://blog.csdn.net/To_be_to_thought/article/details/85779571。
思路二:
class Solution {
public int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (target == nums[mid])
return mid;
if (nums[mid] < nums[lo]) {
// 6,7,0,1,2,3,4,5
if (target < nums[mid] || target >= nums[lo])
hi = mid - 1;
else
lo = mid + 1;
} else {
// 2,3,4,5,6,7,0,1
if (target > nums[mid] || target < nums[lo])
lo = mid + 1;
else
hi = mid - 1;
}
}
return -1;
}
}