Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
[2, 2, 1, 1, 1, 2, 2]
22 和 11 抵消
[1, 2, 2]
1 和 2 抵消
[2]
2 即为答案
[2, 3, 1, 4, 1, 1, 1, 1]
2 和 3 抵消
[1, 4, 1, 1, 1, 1]
1 和 4 抵消
[1, 1, 1, 1]
1 即为答案
class Solution {
public:
int majorityElement(vector<int>& nums) {
int cnt = 0;
int res = INT_MIN;
for (auto& x : nums) {
if (cnt == 0) {
res = x;
}
if (res == x) {
++cnt;
} else {
--cnt;
}
}
return res;
}
};