Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
解题思路:摩尔投票法。这种投票法先将第一个数字假设为众数,然后把计数器设为1,比较下一个数和此数是否相等,若相等则计数器加一,反之减一。
实现代码:
// Runtime: 20 ms class Solution { public: int majorityElement(vector<int>& nums) { int n = nums[0]; int c = 1; for (int i = 0; i < nums.size(); i++) { n == nums[i] ? c++ : c--; if (c == 0) { n = nums[i]; c = 1; } } return n; } };