首页 > 代码库 > 81. Search in Rotated Sorted Array II
81. Search in Rotated Sorted Array II
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的启发,两者结合起来做就可以了,代码如下:
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }</style>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]==target) return true;
if(nums[mid]<nums[right]){
if(target>nums[mid]&&target<nums[right]){
left = mid+1;
}else if(target==nums[right]) return true;
else{
right = mid-1;
}
}else if(nums[mid]>nums[right]){
if(target>nums[left]&&target<nums[mid]){
right = mid-1;
}else if(target==nums[left]) return true;
else{
left = mid+1;
}
}else{
right--;
}
}
return nums[left]==target?true:false;
}
}
这道题开始我想用先找最小元素然后在找制定元素来做,但是没有通过。原因是这时候realmid和realend是相等的,而此时的nums【realmid】是不等于target的,代码如下:
<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px "Helvetica Neue"; color: #454545 }</style>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;
}
}
红线部分想改进但是不知道怎么改。
81. Search in Rotated Sorted Array II