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

169. 多数元素

目录

题目链接

题目

解题思路

代码


题目链接

169. 多数元素 - 力扣(LeetCode)

题目

解题思路

法一:哈希表统计个数

法二:摩尔投票法,相同+1,不同-1,最后剩下的肯定是大于n/2的元素的值

代码

法一:

class Solution {private Map<Integer,Integer> ountNums(int[] nums){Map<Integer,Integer> counts=new HashMap<Integer,Integer>();for(int num:nums){if(!counts.containsKey(num)){counts.put(num,1);}else{counts.put(num,counts.get(num)+1);}}return counts;}public int majorityElement(int[] nums) {Map<Integer,Integer>  counts=ountNums(nums);Map.Entry<Integer,Integer> majority=null;for(Map.Entry<Integer,Integer> entry:counts.entrySet()){if(majority==null||entry.getValue()>majority.getValue()){majority=entry;}}return majority.getKey();}
}

法二:

class Solution {public int majorityElement(int[] nums) {int x=0,val=0;for(int num:nums){if(val==0) x=num;val+=x==num?1:-1;}return x;}
}


文章转载自:
http://accusative.elldm.cn
http://cassaba.elldm.cn
http://cdsl.elldm.cn
http://askant.elldm.cn
http://cambrel.elldm.cn
http://allegheny.elldm.cn
http://chemomorphosis.elldm.cn
http://caldarium.elldm.cn
http://bipolar.elldm.cn
http://arroyo.elldm.cn
http://aegeus.elldm.cn
http://also.elldm.cn
http://blaw.elldm.cn
http://antilabor.elldm.cn
http://avenue.elldm.cn
http://captan.elldm.cn
http://beret.elldm.cn
http://chesty.elldm.cn
http://bypass.elldm.cn
http://bummalo.elldm.cn
http://asthenosphere.elldm.cn
http://cdrom.elldm.cn
http://bluster.elldm.cn
http://chemakuan.elldm.cn
http://calabash.elldm.cn
http://cgh.elldm.cn
http://bryozoa.elldm.cn
http://antiutopian.elldm.cn
http://asiadollar.elldm.cn
http://blivit.elldm.cn
http://www.dtcms.com/a/276614.html

相关文章:

  • 二分搜索 (左程云)
  • 【Docker基础】Dockerfile核心概念解析:什么是Dockerfile?与镜像、容器的关系
  • shiro550反序列化漏洞复现(附带docker源)
  • AV1比特流结构
  • zynq-PS篇——bperez77中DMA驱动注意事项
  • 车载以太网-旁路配置
  • MyBatis基于XML配置详细使用指南
  • IMU姿态传感器
  • 栈题解——最小栈【LeetCode】
  • 学历一般,基础一般还有必要刷算法题吗
  • 一种Φ325海底管道机械三通结构设计cad【1张】三维图+设计说明书
  • python学习笔记【1】对字符串的处理
  • 网络安全day1-2笔记
  • kettle从入门到精通 第101课 ETL之kettle DolphinScheduler调度kettle
  • RAG进阶之术:用“父子Chunk”策略破解复杂查询的“上下文迷局”
  • Win11怎样进入WinRE恢复环境
  • 并发--Callable vs Runnable
  • 深入理解 Boost.Asio 中的异步核心 boost::asio::io_context
  • AI智能体|扣子(Coze)搭建【裸眼3D著名故事动画视频】工作流
  • NOIP普及组|2005T1淘淘摘苹果
  • 常用控件QWidget
  • 部署Harbor私有仓库
  • 第五章 RAG知识库进阶
  • Java项目2——增强版飞机大战游戏
  • Linux:信号
  • Redis持久化机制:RDB和AOF
  • 【面试八股文】2025最新软件测试面试
  • 多模态数据解压-Parquet
  • 【数据结构初阶】--顺序表(三)
  • 咨询导览,AI发展趋势