-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathguess-the-majority-in-a-hidden-array.cpp
41 lines (40 loc) · 1.22 KB
/
guess-the-majority-in-a-hidden-array.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
// Time: O(n), n queries
// Space: O(1)
class Solution {
public:
int guessMajority(ArrayReader &reader) {
int count_a = 1, count_b = 0, idx_b = -1;
const auto& value_0_1_2_3 = reader.query(0, 1, 2, 3);
int value_0_1_2_i = -1;
for (int i = reader.length() - 1; i >= 4; --i) {
value_0_1_2_i = reader.query(0, 1, 2, i);
if (value_0_1_2_i == value_0_1_2_3) { // nums[i] == nums[3]
++count_a;
} else {
++count_b;
idx_b = i;
}
}
const auto& value_0_1_2_4 = value_0_1_2_i;
for (int i = 0; i < 3; ++i) {
vector<int> a_b;
for (int j = 0; j < 3; ++j) {
if (j == i) {
continue;
}
a_b.emplace_back(j);
}
const auto& value_a_b_3_4 = reader.query(a_b[0], a_b[1], 3, 4);
if (value_a_b_3_4 == value_0_1_2_4) { // nums[i] == nums[3]
++count_a;
} else {
++count_b;
idx_b = i;
}
}
if (count_a == count_b) {
return -1;
}
return count_a > count_b ? 3 : idx_b;
}
};