一个数组找出出现次数最多的一个数,如果多个数出现的次数相同则输出第一个,代码演示
时间: 2023-12-06 11:44:46 浏览: 38
可以使用哈希表来解决这个问题,遍历一遍数组,将每个数字出现的次数记录在哈希表中,最后再遍历一遍哈希表,找出出现次数最多的数字。
以下是示例代码:
```python
def find_most_frequent_number(arr):
hash_table = {}
max_count = 0
most_frequent_number = None
for num in arr:
if num in hash_table:
hash_table[num] += 1
else:
hash_table[num] = 1
if hash_table[num] > max_count:
max_count = hash_table[num]
most_frequent_number = num
return most_frequent_number
arr = [1, 2, 3, 4, 5, 6, 2, 3, 3, 3, 2]
print(find_most_frequent_number(arr)) # Output: 3
```
在上面的代码中,我们使用了一个哈希表 `hash_table` 来记录每个数字出现的次数,同时使用 `max_count` 和 `most_frequent_number` 两个变量来记录出现次数最多的数字和其出现的次数。遍历哈希表时,如果一个数字的出现次数大于 `max_count`,则更新 `max_count` 和 `most_frequent_number` 的值。最后返回 `most_frequent_number` 即可。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)