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.
Difficulty: Hard
Solution 1: O(n), the simplest way.
public class Solution {
public int search(int[] nums, int target) {
int i = 0;
int len = nums.length;
while(i < len){
if(target == nums[i])
return i;
i++;
}
return -1;
}
}
Solution 2: O(logn), Binary Search.
public class Solution {
public int search(int[] nums, int target) {
return binSearch(nums, 0, nums.length-1, target);
}
public int binSearch(int[] nums, int start, int end, int target){
if(start > end)
return -1;
int mid = start + (end-start)/2;
if(nums[mid] == target)
return mid;
if(nums[mid] >= nums[start]){
if(target >= nums[start] && target < nums[mid]){
return binSearch(nums, start, mid - 1, target);
}
else{
return binSearch(nums, mid + 1, end, target);
}
}
else{
if(target <= nums[end] && target > nums[mid]){
return binSearch(nums, mid + 1, end, target);
}
else{
return binSearch(nums, start, mid - 1, target);
}
}
}
}
Solution 1: O(n), the simplest way.