数组中出现次数最多的数及出现次数
时间: 2023-10-17 08:05:31 浏览: 91
要查找数组中出现次数最多的数及出现次数,可以使用哈希表来统计每个数字出现的次数,然后找到出现次数最多的数字即可。
以下是 Python 代码实现:
```python
from collections import defaultdict
def find_most_frequent(arr):
freq_dict = defaultdict(int)
for num in arr:
freq_dict[num] += 1
max_freq = 0
max_num = None
for num, freq in freq_dict.items():
if freq > max_freq:
max_freq = freq
max_num = num
return max_num, max_freq
```
使用示例:
```python
arr = [1, 3, 2, 2, 1, 1, 4, 5, 4, 4]
max_num, max_freq = find_most_frequent(arr)
print(f"The most frequent number is {max_num} and it appears {max_freq} times.")
# 输出:The most frequent number is 1 and it appears 3 times.
```
时间复杂度为 O(n),空间复杂度为 O(n)。