写一个查找数组中出现次数最多的数
时间: 2024-05-12 14:16:58 浏览: 19
可以使用HashMap来解决此问题。首先遍历一遍数组,将数组中的每个数作为key,出现次数作为value存入HashMap中。然后遍历一遍HashMap,找到value最大的key即可。
Java代码如下:
```java
public static int findMostFrequent(int[] arr) {
HashMap<Integer, Integer> map = new HashMap<>();
// 统计每个数出现的次数
for (int num : arr) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
int maxCount = 0, maxNum = arr[0];
// 找出出现次数最多的数
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
maxNum = entry.getKey();
}
}
return maxNum;
}
```
相关问题
用c语言查找数组中出现次数最多的数
可以使用哈希表来查找出现次数最多的数。
具体步骤如下:
1. 声明一个哈希表,用来记录每个数出现的次数。
2. 遍历数组,将每个数在哈希表中对应的值加1。
3. 找到哈希表中值最大的键,即为出现次数最多的数。
以下是示例代码:
```c
#include <stdio.h>
#define SIZE 1000
int main()
{
int arr[SIZE];
int n, max_num = -1, max_count = 0;
int hash[SIZE] = {0};
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
hash[arr[i]]++;
if (hash[arr[i]] > max_count) {
max_count = hash[arr[i]];
max_num = arr[i];
}
}
printf("The number that appears the most is %d, which appears %d times.\n", max_num, max_count);
return 0;
}
```
注:此方法假设数组中所有数均为正整数且小于等于SIZE。如果不是,则需要调整SIZE的大小。
数组中出现次数最多的数及出现次数
要查找数组中出现次数最多的数及出现次数,可以使用哈希表来统计每个数字出现的次数,然后找到出现次数最多的数字即可。
以下是 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)。