当前位置:网站首页>169. 多数元素
169. 多数元素
2022-04-21 17:07:00 【不爱研究的研究僧】
题目:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
题解:
- 利用哈希表统计每个数字的个数
- 找出value即个数最多的那个entry,因为比较的是value,但返回的是key,因此要用的结果是entry
注意:set是contains(),map是containsKey();
map中获取某个key的value用的是get();
entry获取key用的是getKey(),entry获取value用的是getValue()
class Solution {
public int majorityElement(int[] nums) {
Map<Integer, Integer> map = countNums(nums);
Map.Entry<Integer, Integer> res = null; //Map.Entry表示Map中的一个实体(一个key-value对)
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (res == null || res.getValue() < entry.getValue()) { //如果结果entry为空或者value小于当前entry的value,替换结果entry
res = entry;
}
}
return res.getKey();
}
//统计数字的个数,返回哈希表
public Map<Integer, Integer> countNums(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (!map.containsKey(num)) {
map.put(num, 1);
} else {
map.put(num, map.get(num) + 1);
}
}
return map;
}
}
参考:力扣
版权声明
本文为[不爱研究的研究僧]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43955488/article/details/124326005
边栏推荐
- 幹貨 | 實戰演練基於加密接口測試測試用例設計
- 【一篇文章帮你打好路由基础】
- Program design TIANTI race l3-29 restore file (DFS is over, leaving the original spectrum)
- Quick MTF, lens image quality test application
- 29. 有 1、2、3、4 个数字,能组成多少个互不相同且无重复数字的三位数
- When you encounter technical problems
- 解读论文记录 指出经典的RMS证明过程小错误的一个论文的解读
- Multilingual communication foundation 04 grpc and protobuf
- Design and practice of unified security authentication for microservice architecture
- mysql主键id自定义
猜你喜欢

The first five chapters are thought maps

把握住这5点!在职考研也能上岸!

Summary of Wu Enda's course of machine learning (5)

Quick MTF, lens image quality test application

Quick MTF,镜头图像质量测试应用程序

How to judge whether a binary differential equation is a total differential

ls -al各字段意思

Win10桥接网卡使得qemu虚拟机可以正常访问网络

Precautions for MySQL aliasing database tables
![[an article helps you lay a good foundation for routing]](/img/3d/1c0329c39c0c5282db841db970a060.png)
[an article helps you lay a good foundation for routing]
随机推荐
微机原理与接口技术——电子琴实验报告
Database Principle -- library management system
2-4. Port binding
R语言使用plot函数可视化数据散点图,使用par函数中的bg参数自定义设置可视化图像线框内的背景色
Summary of Wu Enda's course of machine learning (I)
幹貨 | 實戰演練基於加密接口測試測試用例設計
Summary of Wu Enda's course of machine learning (4)
thrift简单应用
sqli-labs 23-25a关闯关心得与思路
众测、专属、渗透测试捡破烂小tips
The rebound base has an FD
1044. Longest repeating substring
Binary tree related creation or traversal
不同环境下控制@Schedule 开启
824. 山羊拉丁文
/Utilization of etc / passwd
R language data export (data saving, export and persistence to local specified directory file), write using xlsx package Xlsx function exports dataframe to excel file XLS format instead of xlsx format
Microcomputer principle and interface technology -- electronic organ experiment report
pytorch index_add_用法介绍
CSP Darknet53