Follow up for "Find Minimum 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).
Find the minimum element.
The array may contain duplicates.
int findMin(int* nums, int numsSize)
{
if(numsSize == 0)
{
return 0;
} else if(numsSize == 1)
{
return nums[0];
} else if(numsSize == 2)
{
return (nums[0] > nums[1]) ? nums[1] : nums[0];
}
int start = 0;
int end = numsSize -1;
int mid = 0;
while(start < end - 1)
{
/*数组有序递增*/
if(nums[start] < nums[end])
return nums[start];
/*计算mid注意方法*/
mid = start + (end - start) / 2;
if(nums[start] > nums[mid])
end = mid;
else if (nums[start] < nums[mid])
start = mid;
else
start = start + 1;
}
return (nums[start] > nums[end]) ? nums[end] : nums[start];
}