-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path07-minNumberInRotateArray.cpp
More file actions
73 lines (66 loc) · 1.5 KB
/
07-minNumberInRotateArray.cpp
File metadata and controls
73 lines (66 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/********************************
*@file:
*@author: Pan HU
*@data: 2015-8-16
*@version: 0.1
*@describe:
********************************/
#include <iostream>
#include <vector>
#include <stdexcept>
#include <exception>
using namespace std;
int minNumberInRotateArray(vector<int> rotateArray);
int main()
{
int arr[] = {3,4,5,1,2};
vector<int> vec/*(arr,arr+sizeof(arr)/sizeof(*arr))*/;
try{
cout<<minNumberInRotateArray(vec)<<endl;
} catch (const runtime_error &e){
cerr<<e.what()<<endl;
}
vec.push_back(2);
vec.push_back(1);
cout<<minNumberInRotateArray(vec)<<endl;
return 0;
}
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.empty())
{
throw runtime_error("array is empty!");
}
int indexLeft = 0;
int indexRight = rotateArray.size()-1;
int indexMid = 0;
while(rotateArray[indexLeft] >= rotateArray[indexRight])
{
if(indexRight - indexLeft == 1)
{
return rotateArray[indexRight];
}
indexMid = (indexLeft + indexRight)/2;
if(rotateArray[indexLeft] == rotateArray[indexRight]
&& rotateArray[indexLeft] == rotateArray[indexMid])
{
int minItem = rotateArray[indexLeft];
for(int i = indexLeft+1; i <= indexRight; ++i)
{
if(rotateArray[i] < minItem)
{
minItem = rotateArray[i];
}
}
return minItem;
}
if(rotateArray[indexMid] >= rotateArray[indexLeft])
{
indexLeft = indexMid;
}
else if(rotateArray[indexMid] <= rotateArray[indexRight])
{
indexRight = indexMid;
}
}
return rotateArray[indexMid];
}