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.
在翻转过的包含重复数的数组中查找元素。
思路一:直接遍历。也能AC……
public class Solution {
public bool Search(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] == target)
return true;
}
return false;
}
}
思路二:
因为重复的原因,可能左右两端数值相同,使我们失去二分挑边的功能。解决办法是对边缘移动一步,直到边缘和中间不在相等或者相遇。所以最坏情况(比如全部都是一个元素,或者只有一个元素不同于其他元素,而他就在最后一个)就会出现每次移动一步,总共是n步,算法的时间复杂度变成O(n)。
思路参考:http://blog.csdn.net/linhuanmars/article/details/20588511
public bool search(int[] nums, int target) {
if(nums==null || nums.Length==0)
return false;
int l = 0;
int r = nums.Length-1;
while(l<=r)
{
int m = (l+r)/2;
if(nums[m]==target)
return true;
if(nums[m]>nums[l])
{
if(nums[m]>target && nums[l]<=target)
{
r = m-1;
}
else
{
l = m+1;
}
}
else if(nums[m]<nums[l])
{
if(nums[m]<target && nums[r]>=target)
{
l = m+1;
}
else
{
r = m-1;
}
}
else
{
l++;
}
}
return false;
}