当前位置: 首页 > news >正文

leetCode 229. 多数元素 II + 摩尔投票法 + 进阶 + 优化空间

229. 多数元素 II - 力扣(LeetCode)


给定一个大小为 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。 


(1)哈希表

class Solution {
public:// 哈希vector<int> majorityElement(vector<int>& nums) {unordered_map<int,int> mp;for(const int& a:nums) mp[a]++;int n = nums.size() / 3;int i=0;vector<int> ans;for(auto &it:mp) {if(it.second > n) ans.push_back(it.first); }return ans;}
};

(2) 摩尔投票法

class Solution {
public:// 摩尔投票法vector<int> majorityElement(vector<int>& nums) {// 创建返回值vector<int> res;if (nums.empty() || nums.size() == 0) return res;// 初始化两个候选人candidate,和他们的计票int cand1 = nums[0],count1 = 0;int cand2 = nums[0],count2 = 0;// 摩尔投票法,分为两个阶段:配对阶段 和 计数阶段// (1) 配对阶段for(const int &num : nums) {// 投票if(cand1 == num) {count1++;continue;}if(cand2 == num) {count2++;continue;}// 第 1 个候选人配对if(count1 == 0) {cand1 = num;count1++;continue;}// 第 2 个候选人配对if(count2 == 0) {cand2 = num;count2++;continue;}count1--;count2--;}// (2)计数阶段 : 找到了两个候选人之后,需要确定票数是否满足大于 N/3count1=0;count2=0;for(const int &num : nums) {if (cand1 == num) count1++;else if (cand2 == num) count2++;}if (count1 > nums.size() / 3) res.push_back(cand1);if (count2 > nums.size() / 3) res.push_back(cand2);return res;}
};

推荐和参考文章:

229. 多数元素 II - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/majority-element-ii/solutions/123170/liang-fu-dong-hua-yan-shi-mo-er-tou-piao-fa-zui-zh/229. 多数元素 II - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/majority-element-ii/solutions/1060343/gong-shui-san-xie-noxiang-xin-ke-xue-xi-ws0rj/

http://www.lryc.cn/news/209778.html

相关文章:

  • 5 个编写高效 Makefile 文件的最佳实践
  • 20231028刷题记录
  • 39 深度学习(三):tensorflow.data模块的使用(基础,可跳)
  • css四种导入方式
  • Linux学习第24天:Linux 阻塞和非阻塞 IO 实验(一): 挂起
  • 037-第三代软件开发-系统音量设置
  • Python 自动化详解(pyautogui)
  • 【Linux】第四站:Linux基本指令(三)
  • SpringBoot内置工具类之断言Assert的使用与部分解析
  • 如何检测租用的香港服务器是不是CN2线路呢?
  • Spring Boot进阶(94):从入门到精通:Spring Boot和Prometheus监控系统的完美结合
  • Redis(02)| 数据结构-SDS
  • HackTheBox-Starting Point--Tier 0---Preignition
  • 售货机相关的电路
  • 软考高项(十四)项目沟通管理 ★重点集萃★
  • Linux多线程服务端编程:使用muduo C++网络库 学习笔记 第五章 高效的多线程日志
  • 利用Pholcus框架提取小红书数据的案例分析
  • 超详细Hadoop安装教程(单机版、伪分布式)
  • 持续集成部署-k8s-服务发现-Ingress
  • 从零开始搭建Prometheus+grafana服务器组件监控系统
  • 智能水厂运行与调控3D模拟仿真在线展示提高整个系统的协同效应
  • ts声明文件
  • JPA联合主键使用
  • 【计算机毕设经典案例】基于微信小程序的图书管理系统
  • 如何制作rpm离线安装包
  • golang中快速用melody搭建轻量的websocket服务
  • ​Profinet转EtherNET/IP从站连接欧姆龙plc与西门子200smart通讯的配置方法​
  • elementUI el-table实现鼠标悬浮某一行,在鼠标右侧展示提示信息
  • Java 使用 poi 和 aspose 实现 word 模板数据写入并转换 pdf 增加水印
  • Spring Boot进阶(93):体验式教程:手把手教你整合Spring Boot和Zipkin