Search in Rotated Sorted Array II
Total Accepted: 35100 Total Submissions: 111308My Submissions
Question Solution
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.
Show Tags
分析:二分搜索法
public class Solution {
boolean findnum(int[] nums, int target, int s, int e){
if(s==e)
{
if(nums[s]==target)
return true;
else
return false;
}
else
{
if(nums[s]<nums[e])
{
if(nums[s]>target||target>nums[e])
return false;
else
{
int mid=s+(e-s)/2;
if(target==nums[mid])
return true;
else if(target<nums[mid])
return findnum(nums, target, s, mid);
else
return findnum(nums, target, mid+1,e);
}
}
else
{
if(target==nums[e]||target==nums[s])
return true;
else if(target>nums[e]&&target<nums[s])
{
return false;
}
else
{
int mid=s+(e-s)/2;
if(target==nums[mid])
return true;
else
{
boolean l=findnum(nums, target, s, mid);
boolean r=findnum(nums, target, mid+1, e);
if(l||r)
return true;
else
return false;
}
}
}
}
}
public boolean search(int[] nums, int target) {
int size=nums.length;
if(size==0)
return false;
else
{
return findnum(nums, target, 0, size-1);
}
}
}