if the middle value locates in the first increasing part, the mini value must locate at the lower half, thus, the first pointer
should point to the middle instead.
if the middle value locates in the second increasing part, the mini value must be smaller or equals to the second pointer.
#include <iostream>
#include <vector>
using namespace std;
/*
Given a sorted array rotated in some point, find the minimum number.
Example:
3, 4, 5, 0, 1, 2
return 0
1, 1, 1, 1, 0, 1
return 0
*/
int minInOrder(vector<int>& nums, int start, int end) {
int result = nums[start];
for(int i = start + 1; i <= end; ++i) {
if(result > nums[i]) result = nums[i];
}
return result;
}
int findMinimumNumber(vector<int>& nums) {
int start = 0;
int end = nums.size() - 1;
int indexMid = start;
while(nums[start] >= nums[end]) {
if(end - start == 1) {
indexMid = end;
break;
}
int indexMid = (start + end) / 2;
// if start, end and indexMid all point to the same number.
if(nums[start] == nums[end] && nums[indexMid] == nums[start])
//search linarly.
return minInOrder(nums, start, end);
if(nums[indexMid] >= nums[start]) start = indexMid;
else if(nums[indexMid] <= nums[end]) end = indexMid;
}
return nums[indexMid];
}
int main(void) {
vector<int> nums{1, 0, 1, 1, 1, 1};
//vector<int> nums{1, 0, 1, 1, 1, 1};
cout << findMinimumNumber(nums) << endl;
}
A optimized way: do it as the same as search number in rotated sorted array.
#include "header.h"
using namespace std;
int findMini(vector<int>& nums) {
if(nums.size() == 0) return -1;
int left = 0, right = nums.size() - 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--;
}
return nums[right];
}
int main(void) {
vector<int> nums{0, 1, 1};
cout << findMini(nums) << endl;
}