思想来自维基百科
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
LeetCode 中有这样一题:
/************************************************************************
*
* 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.
*
* Credits:Special thanks to @ts for adding this problem and creating all test cases.
*
************************************************************************/
此题有很多种方法,但是有一种Boyer–Moore majority vote algorithm可以达到时间复杂度O(N),空间复杂度O(1).
基本思想(来自维基百科)
The algorithm is carried out in two steps:
1.消除除所要元素之外的所有元素。
Iterating through the array of numbers, maintain a current candidate and a counter initialized to 0. With the current element x in iteration, update the counter and (possibly) the candidate: if the counter is 0, set the current candidate to x and the counter to 1. If the counter is not 0, increment or decrement the counter based on whether x is the current candidate.
通过对矩阵迭代,保持当前候选和一个计数器初始化为0。随着迭代的当前元素x ,更新计数器和(可能)候选者:如果计数器是0,设置当前候选者为x和计数器为1。如果计数器不为0,如果当前元素等于x,则计数器加1,否则将1.
2.确定如果剩余元素是有效的多数元件。
With the candidate acquired in step 1, iterate through the array of numbers and count its occurrences. Determine if the result is more than half of the sequence’s length. If so, the candidate is the majority. Otherwise, the sequence doesn’t contain a majority.
在步骤1中遍历矩阵获取的候选人,并计算其发生。确定如果结果大于序列的长度的一半以上。如果是这样,候选是多数。否则,该序列不包含多数。
附上代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int major, counts = 0, n = nums.size();
for (int i = 0; i < n; i++) {
if (!counts) {
major = nums[i];
counts = 1;
}
else counts += (nums[i] == major) ? 1 : -1;
}
return major;
}
};
其余的方法
哈希表,时间复杂度o(n)
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counts;
int n = nums.size();
for (int i = 0; i < n; i++)
if (++counts[nums[i]] > n / 2)
return nums[i];
return 0;
}
};
排序时间复杂度O(nlogn)
// sort ,but it O(nlogn)
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size() / 2];
}