当前位置:网站首页>每日3题(2)- 找出数组中的幸运数
每日3题(2)- 找出数组中的幸运数
2022-06-25 10:24:00 【程序猿不脱发2】
题目:
在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。
给你一个整数数组 arr,请你从中找出并返回一个幸运数。
如果数组中存在多个幸运数,只需返回 最大 的那个。
如果数组中不含幸运数,则返回 -1 。
示例 1:
输入:arr = [2,2,3,4]
输出:2
解释:数组中唯一的幸运数是 2 ,因为数值 2 的出现频次也是 2 。
示例 2:
输入:arr = [1,2,2,3,3,3]
输出:3
解释:1、2 以及 3 都是幸运数,只需要返回其中最大的 3 。
示例 3:
输入:arr = [2,2,2,3,3]
输出:-1
解释:数组中不存在幸运数。
示例 4:
输入:arr = [5]
输出:-1
示例 5:
输入:arr = [7,7,7,7,7,7,7]
输出:7
提示:
1 <= arr.length <= 500
1 <= arr[i] <= 500
思路:
hash映射
java代码:
class Solution {
public int findLucky(int[] arr) {
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int x : arr) {
m.put(x, m.getOrDefault(x, 0) + 1);
}
int ans = -1;
for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
int key = entry.getKey(), value = entry.getValue();
if (key == value) {
ans = Math.max(ans, key);
}
}
return ans;
}
}
边栏推荐
猜你喜欢
Unreal Engine graphics and text notes: use VAT (vertex animation texture) to make Houdini end on Houdini special effect (ue4/ue5)
网络协议学习---LLDP协议学习
Opencv learning (II) -- installing opencv on raspberry pie
Houdini graphic notes: could not create OpenCL device of type (houdini_ocl_devicetype) problem solving
Use of Siemens plcs7-200 (I) -- Introduction to development environment and configuration software
The left sliding menu +menu item icon is grayed out
Flask blog practice - archiving and labeling of sidebar articles
1-7snapshots and clones in VMWare
Es learning
【历史上的今天】6 月 24 日:网易成立;首届消费电子展召开;世界上第一次网络直播
随机推荐
Kotlin implements a simple login page
性能之文件系统篇
Floating window --- create an activity floating window (can be dragged)
Solutions using protobuf in TS projects
The title of my composition is - "my district head father"
Mqtt beginner level chapter
[paper reading | deep reading] drne:deep recursive network embedding with regular equivalence
Dell technology performs the "fast" formula and plays ci/cd
Shardingsphere proxy 5.0 sub database and sub table (I)
FPGA基于VGA显示字符及图片
我希望按照我的思路盡可能將canvas基礎講明白
What is CRA
【观察】ObjectScale:重新定义下一代对象存储,戴尔科技的重构与创新
Learn to learn self-study [learning to learn itself is more important than learning anything]
1-7snapshots and clones in VMWare
国信证券证券账户开户安全吗
《天天数学》连载52:二月二十日
Identityserver4 definition concept
Oracle彻底卸载的完整步骤
ES 学习