力扣练习第三十八天——求众数
题目大致如下:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例一:
输入: [3,2,3]
输出: 3
示例二:
输入: [2,2,1,1,1,2,2]
输出: 2
链接来源于LeetCode:https://leetcode-cn.com/problems/majority-element/
大致思路:
采用摩尔投票算法,设置一个临时变量x,然后再从头到尾进行遍历,遍历完毕后x的取值为众数。
代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int x = nums[0];
int a = 0;
for (int t : nums){
if (a==0) x=t;
if(t==x) a++;
else a--;
}
return x;
}
};
结果: