-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchInRotated.cpp
123 lines (97 loc) · 2.34 KB
/
searchInRotated.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
113
114
115
116
117
118
119
120
121
122
123
#include<vector>
#include<iostream>
/*
https://leetcode.com/problems/search-in-rotated-sorted-array/
*/
namespace searchInRotated{
int search(std::vector<int>& nums, int target) {
int count = 0;
while(true){
int first = nums[0];
int size = nums.size();
if(first == target)
return count;
if(size == 1 and first != target)
return -1;
int mid = nums[size / 2];
if (mid == target)
return count + (size / 2);
if (size <= 2)
return -1;
bool con1 = first > target;
bool con2 = mid > target;
bool con3 = mid > first;
bool con4 = first < mid;
if (con1 and con2 and con3) {
nums.erase(nums.begin(), nums.begin() + (size / 2) + 1);
count += (size / 2) + 1;
}
else if (con1 and con2 and not con3) {
nums.erase(nums.begin() + (size / 2) + 1, nums.end());
}
else if (con1 and not con2) {
nums.erase(nums.begin(), nums.begin() + (size / 2) + 1);
count += (size / 2) + 1;
}
else if (not con1 and con2) {
nums.erase(nums.begin() + (size / 2) + 1, nums.end());
}
else if(not con1 and not con2 and con4){
nums.erase(nums.begin(), nums.begin() + (size / 2) + 1);
count += (size / 2) + 1;
}
else if (not con1 and not con2 and not con4) {
nums.erase(nums.begin() + (size / 2) + 1, nums.end());
}
else {
//The target value is NOT in the array.
return -1;
}
}
}
//Check all the test-cases.
bool searchInRotated_Test(){
//Test-case 1:
std::vector<int> v = { 4,5,6,7,0,1,2 };
if(search(v, 0) != 4)
return false;
//Test-case 2:
v = { 4,5,6,7,0,1,2 };
if(search(v, 3) != -1)
return false;
//Test-case 3:
v = { 1 };
if(search(v, 0) != -1)
return false;
//Test-case 4:
v = { 2,4,5,6,7,0,1 };
if (search(v, 5) != 2)
return false;
//Test-case 5:
v = { 7,8,1,2,3,4,5,6 };
if (search(v, 2) != 3)
return false;
//Test-case 5:
v = { 1,3 };
if (search(v, 2) != -1)
return false;
//Test-case 6:
v = { 1,2 };
if (search(v, 2) != 1)
return false;
//Test-case 7:
v = { 1,3,5 };
if (search(v, 5) != 2)
return false;
//Test-case 8:
v = { 1,3,5 };
if (search(v, 8) != -1)
return false;
//Test-case 9:
v = { 8,9,2,3,4 };
if (search(v, 9) != 1)
return false;
std::cout << "All test-cases for searchInRotated method passed." << std::endl;
return true;
}
}