题目是LeetCode第182场周赛的第一题,链接:找出数组中的幸运数。具体描述为:在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。给你一个整数数组 arr,请你从中找出并返回一个幸运数。
- 如果数组中存在多个幸运数,只需返回 最大 的那个。
- 如果数组中不含幸运数,则返回 -1 。
- 1 <= arr.length <= 500
- 1 <= arr[i] <= 500
示例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
首先给出一种通用解法,就是直接用一个map,以数字为key,出现次数为value。最后需要遍历map以找到最大的幸运数。时间复杂度为 ,空间复杂度为 (因为数字的种类数肯定小于等于数组长度n)。
JAVA版代码如下:
class Solution {
public int findLucky(int[] arr) {
Map<Integer, Integer> map = new HashMap<>();
for (int a : arr) {
if (map.containsKey(a)) {
map.put(a, map.get(a) + 1);
}
else {
map.put(a, 1);
}
}
int result = -1;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getKey() == entry.getValue()) {
if (entry.getKey() > result) {
result = entry.getKey();
}
}
}
return result;
}
}
提交结果如下:
然后考虑到数字的范围是有限的(记为N),所以可以直接用一个数组记录各个数出现的范围,找最大的幸运数的时候也只需要从数组尾部往头部遍历,一找到就是最大的幸运数了。时间复杂度为 ,空间复杂度为 。
JAVA版代码如下:
class Solution {
public int findLucky(int[] arr) {
int[] count = new int[501];
for (int a : arr) {
++count[a];
}
for (int i = 500; i > 0; --i) {
if (i == count[i]) {
return i;
}
}
return -1;
}
}
提交结果如下: