-
Notifications
You must be signed in to change notification settings - Fork 14k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
106 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
106 changes: 106 additions & 0 deletions
106
01394-Find-out-the-lucky-number-in-the-array/Article/01394
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
# 1394. 找出数组中的幸运数 | ||
|
||
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。 | ||
> | ||
> 同步博客:https://www.algomooc.com | ||
|
||
题目来源于 LeetCode 上 1394题: 找出数组中的幸运数。,主要涉及哈希表。 | ||
|
||
## 题目 | ||
|
||
在整数数组中,如果一个整数的出现频次和它的数值大小相等,我们就称这个整数为「幸运数」。 | ||
|
||
给你一个整数数组 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 | ||
|
||
## 题目解析 | ||
|
||
1. 遍历arr,用哈希表记录每个数组元素出现的次数 | ||
2. 遍历哈希表,每次找到一个幸运数就和当前的幸运数对比,最后找到最大的幸运数,如果没有找到的话输出-1 | ||
|
||
## 动画理解 | ||
|
||
|
||
<video id="video" controls="" preload="none" > | ||
<source id="mp4" src="../Animation/01394.mp4" type="video/mp4"> | ||
</video> | ||
|
||
## 参考代码 | ||
|
||
|
||
```javaScript | ||
/** | ||
* @param {number[]} arr | ||
* @return {number} | ||
*/ | ||
var findLucky = function(arr) { | ||
let map = new Map() | ||
let maxLucky = -1 | ||
arr.map(i => { | ||
map.set(i, map.get(i)+1 || 1) | ||
}) | ||
map.forEach((key, value)=>{ | ||
if(key == value){ | ||
maxLucky = Math.max(maxLucky, key) | ||
} | ||
}) | ||
return maxLucky | ||
}; | ||
``` | ||
|
||
## 复杂度分析 | ||
|
||
假设元素的个数是n个,那么哈希表中最多有 n 个键值对。 | ||
|
||
时间复杂度:这个算法里有两次遍历,遍历数组的时间复杂度是O(n),遍历哈希表的时间复杂度是O(n),所以最后的时间复杂度就是O(n)。 | ||
|
||
空间复杂度:额外只用了哈希表,哈希表中最多有 n 个键值对,所以空间复杂度是 O(n)。 | ||
|
||
|
||
![](../../Pictures/qrcode.jpg) |