forked from JiauZhang/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzzz.cpp
112 lines (95 loc) · 2.82 KB
/
zzz.cpp
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
* Copyright(c) 2019 Jiau Zhang
* For more information see <https://github.com/JiauZhang/algorithms>
*
* This repo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation
*
* It is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with THIS repo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <exception>
#include <vector>
using namespace std;
int find_min(vector<int> &vec, int start, int end) {
int min = vec[start];
while (start <= end) {
if (min>vec[start])
min = vec[start];
start++;
}
return min;
}
int count = 0;
int minNumberInRotateArray(vector<int> &vec) {
if (vec.size() == 0)
return 0;
if (vec.size() == 1)
return vec[0];
int left = 0;
int right = vec.size() - 1;
int mid = left;
while (vec[left]>=vec[right]) {
cout << "vec[mid]=" << vec[mid] << \
" vec[left]=" << vec[left] << \
" vec[right]=" << vec[right]<< endl;
if (right - left == 1) {
mid = right;
break;
}
mid = (left + right) / 2;
if (vec[left] == vec[right] && \
vec[right] == vec[mid]) {
cout << "equals" << endl;
return find_min(vec, left, right);
}
if (vec[mid] < vec[left]) {
cout << "<" << endl;
right = mid;
} else if (vec[mid] >= vec[left]) {
count++;
if (count > 15)
break;
cout << ">=" << endl;
left = mid;
}
}
return vec[mid];
}
void Test(vector<int> &numbers)
{
try {
int minimum = minNumberInRotateArray(numbers);
cout << "minmum: " << minimum << endl;
} catch(...) {
cout << "Invalid parameters" << endl;
}
}
int main(int argc, char** argv)
{
//int test1[9] = {6, 7, 8, 9, 1, 2, 3, 4, 5};// 1
vector<int> test1;
test1.push_back(6);test1.push_back(7);test1.push_back(8);
test1.push_back(9);test1.push_back(1);test1.push_back(2);
test1.push_back(3);test1.push_back(4);test1.push_back(5);
// int test2[9] = {1, 1, 1, 1, 0, 1, 1, 1, 1};// 0
// int test3[9] = {1, 1, 1, 0, 1, 1, 1, 1, 1};// 0
// int test4[9] = {1, 1, 1, 1, 1, 0, 1, 1, 1};// 0
// int test5[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};// 1
// int test6[2] = {3, 2};// 2
Test(test1);
// Test(test2, 9);
// Test(test2, 9);
// Test(test4, 9);
// Test(test5, 9);
// Test(NULL, 0);
// Test(test6, 2);
return 0;
}