1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
guess-the-majority-in-a-hidden-array.cpp 1.22 KB
一键复制 编辑 原始数据 按行查看 历史
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助