Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Example 2:
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public boolean search(int[] nums, int target) {
int len = nums.length;
if(nums==null || len==0) return false;
int left = 0;
int right = len -1;
int mid;
while(left <= right){
while(left<right && nums[left]==nums[left+1]) ++left;
while(left<right && nums[right]==nums[right-1]) --right;
mid = left + (right - left)/2;
if(nums[mid]==target) return true;
if(nums[left] <= nums[mid]){//左边升序
if(target>=nums[left] && target<nums[mid]){
right = mid -1;
}else{
left = mid+1;
}
}else{
if(target<=nums[right] && target>nums[mid]){
left = mid +1;
}else{
right = mid -1;
}
}
}
return false;
}
}