Description
There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-indexed). For example, [0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become [4,5,6,6,7,0,1,2,4,4].
Given the array nums after the rotation and an integer target, return true if target is in nums, or false if it is not in nums.
Examples
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
Constraints:
1 <= nums.length <= 5000
- 1 0 4 10^4 104 <= nums[i] <= 1 0 4 10^4 104
nums is guaranteed to be rotated at some pivot.
- 1 0 4 10^4 104 <= target <= 1 0 4 10^4 104
解题思路
这道题其实和 #33 Search in Rotated Sorted Array 特别像,只是在33的基础上让每个数字可以重复出现,所以相比于33来说,除了沿用33的循环规律,需要对下面这种情况进行提前处理
input: [1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1]
output: 2
也就是需要确保start和end的数字是不同的数字,对应到代码中就是这样
while(nums[start] == nums[end]){
start ++;
if (start > end){
return nums[start - 1] == target;
}
if (start == end){
return nums[start] == target;
}
}
代码
class Solution {
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(nums[start] == nums[end]){
start ++;
if (start > end){
return nums[start - 1] == target;
}
if (start == end){
return nums[start] == target;
}
}
int middle;
while(true){
if (start >= end)
return nums[start] == target;
middle = (start + end) / 2;
if (nums[middle] == target || nums[start] == target || nums[end] == target)
return true;
if(nums[middle] <= nums[end]){
if (target > nums[middle] && target < nums[end])
start = middle + 1;
else
end = middle - 1;
}
else{
if(target < nums[middle] && target > nums[start])
end = middle - 1;
else
start = middle + 1;
}
}
}
}