Problem: the an array (given all the elements are greater than 0) the beginning of several elements moved to the end of the array, the array we call rotation.
NOTE: If the array size is 0, return 0.
Input: a rotation vector of a non-descending order of the array <int> array
Output: minimum rotating element array.
Ideas: If sequential search, time complexity is O (n), introduces a time where a degree of complexity O (logn) algorithm, based on binary lookup, particularly ideas are as follows:
Establishing two pointers index1 and index2, pointing to the beginning of the head and tail arrays.
a. Since the array is non-descending order, when the array [index1] <array [index2], shows that the rotation has not elapsed, the result is directly output array [index1] to.
b. When array [index1]> = array [index2], the element can not directly find the minimum, taking array [(index1 + index2) / 2] compared with the head and tail.
b.1. In the narrowing process, when index2-index1 == 1, then return index2. Or if (array [index1] == array [index2]) && (array [index1] == array [(index1 + index2) / 2]), you can not use dichotomy to find, only to switch to sequential search
b.2. If the array [index1] <= array [(index1 + index2) / 2], the smallest number in the right half, is assigned to index1 (index1 + index2) / 2
b.3. If the array [index2]> = array [(index1 + index2) / 2], the minimum number of the left half, assigned to the index2 (index1 + index2) / 2
Code:
class Solution {
public:
int minNumberInRotateArray_SequenceFind(vector<int> array)
{
int result=array[0];
int length=array.size();
for(int i=1;i<length;i++)
{
if(array[i]<result)
result=array[i];
}
return result;
}
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.empty())
return 0;
int length=rotateArray.size();
int index1=0;
int index2=length-1;
int midIndex=index1;
while(rotateArray[index1]>=rotateArray[index2])
{
if((index2-index1)==1)
return rotateArray[index2];
midIndex=(index2+index1)/2;
if((rotateArray[index1]==rotateArray[index2])&&(rotateArray[index1]==rotateArray[midIndex]))
return minNumberInRotateArray_SequenceFind(rotateArray);
if(rotateArray[index1]<=rotateArray[midIndex])
index1 = midIndex;
else if(rotateArray[index2]>=rotateArray[midIndex])
index2 = midIndex;
}
return rotateArray[midIndex];
}
};
Complexity Analysis: time complexity of O (n), the spatial complexity is O (1).