Description
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
Write a function to determine if a given target is in the array.
The array may contain duplicates.
Solution
Binary Search, time O(logn) worst O(n), space O(1)
有点tricky的题,因为可能出现nums[left] == nums[mid] == nums[right]的情况,这种情况下只能遍历查找。
而且二分的条件也要改,不是根据nums[mid]和target的比较来决定,而是根据nums[left]和nums[mid]的关系来决定!
class Solution {
public boolean search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target == nums[mid]) {
return true;
} else if (nums[left] < nums[mid]) {
// nums[left, mid] is sorted
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else if (nums[left] > nums[mid]) {
// nums[mid, right] is sorted
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
} else {
++left;
}
}
return false;
}
}
也可以比较nums[mid]和nums[right]:
class Solution {
public boolean search(int[] nums, int target) {
if (nums == null || nums.length < 1) {
return false;
}
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]) {
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
} else if (nums[mid] > nums[right]) {
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
--right;
}
}
return false;
}
}