问题来源
169.Majority Element
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.
Subscribe to see which companies asked this question
问题简述
在一维数组中找到多数元素:在数组中出现次数一半( ⌊ n/2 ⌋)以上。假设多数元素总是存在。
算法来源
A Linear Time Majority Vote Algorithm
算法原文
Majority Vote Algorithm:
We will sweep down the sequence starting at the pointer position shown above.
As we sweep we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.
When we move the pointer forward over an element e:
If the counter is 0, we set the current candidate to e and we set the counter to 1.
If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.
When we are done, the current candidate is the majority element, if there is a majority.
算法简述
在数组中删除每对不同元素,最后得到的便是多数元素。
代码示例
/*keep iterate the array and find pairs of numbers that are different.*/
int majorityElement(vector<int>& nums)
{
int candidate=0;//keep first of the pair.
int count=0;//the number of pairs to be found.
for(int i=0;i!=nums.size();i++)
{
if(count==0)
{
candidate=nums[i];
count=1;
}
else
{
if(candidate==nums[i])//have to find more than one pair.
count++;
else//If found , "delete" the pair(s).
count--;
}
}
return candidate;
}
复杂度分析
时间复杂度O(n) 空间复杂度O(1)