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.
官方代码(思路较清晰):
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 (target < nums[mid] && target >= nums[start])
end = mid - 1;
else
start = mid + 1;
}
if (nums[mid] <= nums[end]){
if (target > nums[mid] && target <= nums[end])
start = mid + 1;
else
end = mid - 1;
}
}
return -1;
}
}
加强版:
81. Search in Rotated Sorted Array II
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
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
思路:重点是单独判断left、medium和right都相等的情况 public boolean search(int[] nums, int target) {
if(nums==null||nums.length==0)return false;
int left=0;
int right=nums.length-1;
while(left<=right)
{
int medium=(left+right)/2;
//equal return
if(target==nums[medium])
{
return true;
}
//left to medium continuous
if(nums[left]==nums[medium]&&nums[medium]==nums[right])
{
left++;
right--;
}
else if(nums[left]<=nums[medium])
{
if(target>=nums[left]&&target<=nums[medium])
{
right=medium-1;
}
else
{
left=medium+1;
}
}
else
{
if(target>=nums[medium]&&target<=nums[right])
{
left=medium+1;
}
else
{
right=medium-1;
}
}
}
return false;
}