[leetcode]81. Search in Rotated Sorted Array II旋转过有序数组里找目标值II(有重)

时间:2021-08-30 09:07:57

This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.

思路

该题是[leetcode]33. Search in Rotated Sorted Array旋转过有序数组里找目标值 的followup

唯一区别是加了line24-26的else语句来skip duplicates

代码

 class Solution {
public boolean search(int[] nums, int target) {
// corner case
if (nums.length == 0) return false;
// init
int left = 0;
int right = nums.length - 1; while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return true;
else if (nums[mid] < nums[right]) { // right side is sorted
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
} else if(nums[mid] > nums[right]){ // left side is sorted
if (target < nums[mid] && target >= nums[left]) {
right = mid - 1;
} else {
left = mid + 1;
}
}else{
right--; //skip duplicats
}
}
return false;
}
}