题目描述
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋
的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例
示例 1:
输入: [3,2,3] 输出: 3
示例 2:
输入: [2,2,1,1,1,2,2] 输出: 2
思路1
排序后,因为众数一定存在,所以众数必为中间数。
时间复杂度(nlogn)
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size = nums.size();
int n = size / 2;
sort(nums.begin(), nums.end());
return nums[n];
}
};
思路2
投票法。因为众数的定义是:出现的次数大于[n/2]。所以假设众数是1,其他数为-1,所以最后相加的结果必大于0。
用投票法的前提是:一定存在众数。
所以设置一个计数器和假设众数值,遍历数组“
(1)若计算器为0,则当前数为假设众数,继续遍历;
(2)若当前数等于当前众数,则计算器加1
(3)若当前数不等于当前众数,则计算器减1
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size = nums.size();
int count = 0;
int cur;
for (int i = 0; i < size; i++){
if (count == 0){
cur = nums[i];
count++;
continue;
}
if (nums[i] == cur) count++;
else count--;
}
return cur;
}
};