Description:
Suppose a sorted array 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.
Solution:
For this problem, we need to use a tricky binary search. First we need to find which part the mid belongs to, then we will find out the target is located in which side of this mid.
import java.io.*;
import java.util.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution {
public int search(int[] nums, int target) {
if (nums == null)
return -1;
int n = nums.length;
int l = 0, r = n - 1, mid;
while (l <= r) {
mid = (l + r) / 2;
if (nums[mid] == target)
return mid;
if (nums[mid] >= nums[l]) {
if (nums[l] <= target && target < nums[mid])
r = mid - 1;
else
l = mid + 1;
} else {
if (nums[mid] < target && target <= nums[r])
l = mid + 1;
else
r = mid - 1;
}
}
return -1;
}
}