LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
[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;
  }
};