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
题目
一个有序数组,可能进行了循环移位,在里面进行查找。
思路
1. We can observe that at least one half of given array is sorted.
2. Find such sorted array part and do binary search
代码
1 class Solution { 2 public int search(int[] nums, int target) { 3 int n = nums.length ; 4 int left = 0, right = n-1; 5 while(left<=right) { 6 int mid = left + (right-left)/2; 7 if(nums[mid]==target) return mid; 8 9 if(nums[mid]<nums[right]) { // right half sorted 10 if(target>nums[mid] && target<=nums[right]) 11 left = mid+1; 12 else 13 right = mid-1; 14 } 15 else if(nums[mid]>nums[right]) { // left half sorted 16 if(target>=nums[left] && target<nums[mid]) 17 right = mid-1; 18 else 19 left = mid+1; 20 } 21 else { 22 right--; 23 } 24 } 25 return -1; 26 } 27 }