【LeetCode】 81. Search in Rotated Sorted Array II 搜索旋转排序数组 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
题目描述:
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
Follow up:
1. This is a follow up problem to Search in Rotated Sorted Array, where nums may contain duplicates.
2. Would this affect the run-time complexity? How and why?
题目大意
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。
编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。
解题方法
和33题类似,只是多了含重复元素【LeetCode】 33. Search in Rotated Sorted Array 搜索旋转排序数组(Medium)(JAVA)
当遇到 mid 和 start 相同时,只要 start + 1,继续即可
class Solution {
public boolean search(int[] nums, int target) {
if (nums.length == 0) return false;
int start = 0;
int end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target) return true;
if (nums[mid] == nums[start]) {
start++;
} else if (nums[mid] > nums[start]) {
if (nums[start] <= target && nums[mid] >= target) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (nums[mid] <= target && nums[end] >= target) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return false;
}
}
执行用时 : 1 ms, 在所有 Java 提交中击败了 83.69% 的用户
内存消耗 : 40 MB, 在所有 Java 提交中击败了 5.79% 的用户