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.
Subscribe to see which companies asked this question
這個題目曾經面試的時候遇到過,當時面試結果是萎了,做這道題目的時候才知道自己爲什麼萎了,這個題目需要考慮六種情況,分別是target和nums[mid]跟nums[0]比較。我當時只是用target跟nums[0]比較。
public class Solution {
public int search(int[] nums, int target) {
if(nums[0]==target){
return 0;
}
int i = 0;int j = nums.length-1;
while(i<=j){
int mid=(i+j)/2;
if(nums[mid]==target){
return mid;
}
else{
if(nums[0]<=target){
if(nums[mid]>=target){
j=mid-1;
}
else{
if(nums[mid]>=nums[0]){
i=mid+1;
}
else{
j=mid-1;
}
}
}
else{
if(nums[mid]>=target){
if(nums[mid]>=nums[0]){
i=mid+1;
}
else{
j=mid-1;
}
}
else{
i=mid+1;
}
}
}
}
return -1;
}
}