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.
class Solution {
public:
int majorityElement(vector<int>& nums) {
int flag=1,x=nums[0];
for(int i=1;i<nums.size();i++)
{
if(nums[i]==x)
flag++;
else
{
flag--;
if(flag==0)
x=nums[i+1];
}
}
return x;
}
};关于摩尔投票法的理解:
1、已被标志清零的元素不会是majority,因为已有相同的元素把它的flag抵消,不满足>n/2。
2、用来抵消的元素没有完全包含majority,因为用来抵消的元素不超过n/2。
3、即majority元素依然 存在于后面没有扫描的部分中,多次反复即可筛选出majority。
本文介绍了一种寻找数组中多数元素的有效算法——摩尔投票法。该算法通过遍历数组并使用标志计数的方式筛选出出现次数超过一半的元素。文章详细解释了该算法的工作原理及其背后的逻辑。
371

被折叠的 条评论
为什么被折叠?



