题目:
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.
题意:最开始想到的是暴力求解,直接遍历数组,时间复杂度为o(n)。可以只用一次二分查找得到结果,时间复杂度为o(logn),因为链表只有一个地方被翻转了,那么肯定可以知道链表若从中间分为两半,一边是肯定有序的;(1)若左边有序,如果target在左边范围,那么继续查找,否则在另一边查找;(2)若右边有序,如果target在右边范围,继续查找,否则在左边查找
代码:
public class Solution { public int search(int[] nums, int target) { int start = 0; int end = nums.length-1; while(start <= end){ int mid = (start + end) / 2; if(nums[mid] == target) return mid; if(nums[start] <= nums[mid]){ //如果链表左边是有序的 if(nums[start] <= target && target < nums[mid]){ //若target在链表左边 end = mid - 1; }else{ start = mid + 1; } } else{ //否则,如果链表右边是有序的 if(nums[end] >= target && target > nums[mid]){ start = mid + 1; }else{ end = mid-1; } } } return -1; } }