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.
此题受到了Search in Rotated Sorted Array以及Find Minimum in Rotated Sorted Array2的启发,两者结合起来做就可以了,代码如下:
1 public class Solution { 2 public boolean search(int[] nums, int target) { 3 if(nums==null||nums.length==0) return false; 4 int low = 0; 5 int high = nums.length-1; 6 while(low<high){ 7 int mid = low +(high-low)/2; 8 if(nums[mid]==target) return true; 9 if(nums[mid]<nums[high]){ 10 if(target>nums[mid]&&target<=nums[high]) low = mid+1; 11 else high = mid-1; 12 }else if(nums[mid]>nums[high]){ 13 if(target>=nums[low]&&target<nums[mid]) high = mid-1; 14 else low = mid+1; 15 }else{ 16 high--; 17 } 18 } 19 return nums[low]==target?true:false; 20 } 21 } 22 //run time complexity O(longn), the space complexity could be O(1);
这道题开始我想用先找最小元素然后在找制定元素来做,但是没有通过。原因是这时候realmid和realend是相等的,而此时的nums【realmid】是不等于target的,代码如下:
public class Solution {
public boolean search(int[] nums, int target) {
if(nums.length==0) return false;
int left = 0;
int right = nums.length-1;
while(left<right){
int mid = left+(right-left)/2;
if(nums[mid]<nums[right]){
right = mid;
}else if(nums[mid]>nums[right]){
left = mid+1;
}else{
right--;
}
}
int min = left;
left = 0;
right = nums.length-1;
while(left<=right){
int mid = left+(right-left)/2;
int realmid = (min+mid)%nums.length;
if(nums[realmid]==target) return true;
else if(nums[realmid]>target) right = mid-1;
else left = mid+1;
}
return false;
}
}
红线部分想改进但是不知道怎么改。