给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
思路:暴力法 排序法 Boyer-Moore 投票算法
解答(C++):
class Solution { public: int majorityElement(vector<int>& nums) { // 暴力法 // std::map<int,int> smap; // for (auto item : nums) { // if (smap.find(item) == smap.end()) { // smap[item] = 1; // } else { // smap[item] = smap[item] + 1; // } // } // int size = 0; // int el = -1; // for (auto it : smap) { // if (it.second > size) { // size = it.second; // el = it.first; // } // } // return el; // 排序法 // std::sort(nums.begin(), nums.end()); // return nums[nums.size()/2]; // Boyer-Moore 投票算法 int candidate = -1; int count = 0; for (auto item : nums) { if (item == candidate) { count++; } else if (--count < 0) { candidate = item; count = 1; } } return candidate; } };
原文:https://www.cnblogs.com/vczf/p/12886467.html