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.
Analysis:
when the duplicate is allowed, so there is one condition that we do not know which is which part of this array is sorted.
public class Solution {
public boolean search(int[] nums, int target) {
int length = nums.length;
if(length == 0)
return false;
return help(nums, target, 0, length - 1);
}
public boolean help(int[] nums, int target, int start, int end){
if(start > end)
return false;
if(start == end)
{
if(nums[start] == target)
return true;
return false;
}
int mid = (start + end) / 2;
if(nums[mid] == target)
return true;
//the logic
// else if(nums[mid] < nums[end] && target > nums[mid])
// return help(nums, target, start + 1, end);
//The first element before rotating is before the mid position
if(nums[mid] < nums[end]){
if(target < nums[mid])
return help(nums, target, start, mid - 1);
else if(target > nums[end])
return help(nums, target, start, mid - 1);
else
return help(nums, target, mid + 1, end);
}
// the first element before rotating is exactely or after the mid position
if(nums[mid] > nums[end]){
if(target > nums[mid])
return help(nums, target, mid + 1, end);
else if(target < nums[start])
return help(nums, target, mid + 1, end);
else
return help(nums, target, start , mid - 1);
}
if(nums[mid] == nums[end]){
boolean temResult = help(nums, target, mid + 1, end);
if(temResult)
return temResult;
else
return help(nums, target, start, mid - 1);
}
return false;
}
}