给定一个大小为 n 的数组 nums ,返回其中的多数元素。多数元素是指在数组中出现次数
大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在多数元素。

- class Solution {
- public:
- int majorityElement(vector<int>& nums) {
- int cand1=0,votes=0;
- for(const int& num:nums) {
- if(votes == 0) cand1 = num;
- // if(cand1 == num) votes++;
- // else votes--;
- votes += (cand1 == num) ? 1 : -1;
- }
- return cand1;
- }
- };
k值摩尔投票法:(推导看我的往期文章)leetCode 229. 多数元素 II + k值摩尔投票法 + 进阶 + 优化空间-CSDN博客
https://blog.csdn.net/weixin_41987016/article/details/134097586?spm=1001.2014.3001.5501
- class Solution {
- public:
- // k值摩尔投票法
- int k=2;
- int majorityElement(vector<int>& nums) {
- // 创建返回值
- vector<int> res;
- // if (nums.empty() || nums.size() == 0) return res;
- if (nums.size() == 1) return nums[0];
- int n = k-1, m = 2, cands[n][m];
- memset(cands, 0, sizeof(cands));
- for(int i=0;i
- cands[i][0]=nums[0];
- // cands[i][1]=0;
- }
-
- // 摩尔投票法,分为两个阶段:配对阶段 和 计数阶段
- bool voteflag=0;
- bool matchflag = 0;
- for(const int &num : nums) {
- // 给候选人投票
- for(int i=0;i
- if(cands[i][0] == num) {cands[i][1]++;voteflag=1;break;}
- else voteflag=0;//投票失败
- }
- // 有某个候选人得票
- if(voteflag) continue;
-
- // 候选人配对
- for(int i=0;i
- if(cands[i][1] == 0) {
- cands[i][0] = num;
- cands[i][1]++;
- matchflag=1;
- break;
- }
- else matchflag=0;
- }
- if(matchflag) continue;
-
- for(int i=0;i
- cands[i][1]--;
- }
- }
- // (2) 计数阶段
- for(int i=0;i
- if(cands[i][1]==0) cands[i][0] = INT_MAX;
- cands[i][1]=0;
- }
- for(const int &num : nums) {
- for(int i=0;i
- if (cands[i][0] == num ) {
- cands[i][1]++;
- }
- }
- for(int i=0;i
- if (cands[i][1] > nums.size() / k ) res.push_back(cands[i][0]);
- }
- return res[0];//这里因为题目要求返回int,有需要可以返回vector
- }
- };
我的往期文章:
-
相关阅读:
vscode基于cmake安装opencv库
牛客多校第三场补题记录
如何将多模态数据融入到BERT架构中-多模态BERT的两类预训练任务
vue3+vite中使用vuex
公司电脑如何限制安装软件
Mysql日志管理、备份与恢复
Redis Lua沙盒绕过命令执行(CVE-2022-0543)
国产化之 .NET Core 操作达梦数据库DM8的两种方式
axios的使用与封装详细教程
【自动控制原理】时域分析法:稳定性分析(稳)、误差分析和计算(准)
-
原文地址:https://blog.csdn.net/weixin_41987016/article/details/134096147