Leetcode 169 Majority Element

这是一道摩尔投票的题目。 后续题目229.Majority Element II

static int x = [] () {ios::sync_with_stdio(false); cin.tie(0); return 0;} ();
class Solution {
 public:
  int majorityElement(vector<int>& nums) {
    int res = nums[0], count = 1;
    for (int i = 1, stop = nums.size(); i < stop; ++i) {
      if (nums[i] == res) {
        ++count;
      } else {
        --count;
        if (count == 0) {
          res = nums[i];
          count = 1;
        }
      }
    }
    return res;
  }
};

#直达链接

LeetCode 169. Majority Element