参考:
https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii/solution/zai-javazhong-ji-bai-liao-100de-yong-hu-by-reedfan/
class Solution:
def search(self, nums, target: int) -> bool:
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
# print(left,mid,right)
if nums[mid] == target:
return True
# 左半段是有序的
if nums[left] < nums[mid]:
# target在这段里
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
# 右半段是有序的
elif nums[left] > nums[mid]:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
else:
left += 1
return False
if __name__ == '__main__':
x = Solution()
nums = [1,3,1,1,1]
target = 3
print(x.search(nums, target))
```
package T81搜索旋转排序数组II;
public class Solution {
public boolean search(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (target == nums[mid]) {
return true;
}
//左半段是有序的
if (nums[start] < nums[mid]) {
//target 在这段里
if (target >= nums[start] && target < nums[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
//右半段是有序的
} else if (nums[start] > nums[mid]) {
if (target > nums[mid] && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
} else {
start += 1;
}
}
return false;
}
}