原题网址:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
方法:二分法查找,注意当头尾相等时,前后两段都需要查找。
public class Solution {
private boolean search(int[] nums, int target, int from, int to) {
if (from > to) return false;
if (from == to) return nums[from] == target;
int m = (from+to)/2;
if (nums[m] == target) return true;
if (nums[from] == nums[to]) return search(nums, target, from, m-1) || search(nums, target, m+1, to);
if (nums[from] < nums[to]) {
if (nums[m] < target) return search(nums, target, m+1, to);
else return search(nums, target, from, m-1);
}
// nums[from] > nums[to]
if (nums[from] <= nums[m]) {
if (nums[from] <= target && target < nums[m]) return search(nums, target, from, m-1);
return search(nums, target, m+1, to);
} else {
if (nums[m] < target && target <= nums[to]) return search(nums, target, m+1, to);
return search(nums, target, from, m-1);
}
//此处错误!!!
// if ((nums[from] <= target && target < nums[m]) || (target < nums[m] && nums[m] <= nums[to])) return search(nums, target, from, m-1);
// return search(nums, target, m+1, to);
}
public boolean search(int[] nums, int target) {
return search(nums, target, 0, nums.length-1);
}
}