1. 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.
用投票法:
Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate. After one pass, the current candidate is the majority element.
Runtime complexity = O(n)
注意:Moore Voting Algorithm要求目标数组存在majority元素(大于n/2),否则需要检验。
int majorityElement(vector<int> &num)
{
int times=1;
int val=num[0];
for(int i=1;i<num.size();i++)
{
if(times==0)
{
val=num[i];
times=1;
}
else if(num[i]!=val)
times--;
else
times++;
}
return val;
}
2.Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
注意:该题目中并没有说存在majority元素(大于n/3)。所以得到候选元素后需要检验。
vector<int> majorityElement2(vector<int>& nums)
{
int num1 = 0, times1 = 0;
int num2 = 0, times2 = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] == num1)
times1++;
else if(nums[i] == num2)
times2++;
else if(times1 == 0)
{
num1 = nums[i];
times1++;
}
else if(times2 == 0)
{
num2 = nums[i];
times2++;
}
else
{
times1--;
times2--;
}
}
times1 = 0;
times2 = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] == num1)
times1++;
else if(nums[i] == num2)
times2++;
}
vector<int> ret;
if(times1 > nums.size()/3)
ret.push_back(num1);
if(times2 > nums.size()/3)
ret.push_back(num2);
return ret;
}
3. 发帖水王问题扩展:有3个发帖很多的ID,他们发帖的数目都超过了帖子总数的1/4,要找出这3个ID。问题类似于在一系列数字中找出出现次数超过1/4的数。