7-9 求整数序列中出现次数最多的数 (15 分)
时间: 2023-05-31 14:20:35 浏览: 260
### 回答1:
题目描述
给定一个长度为n的整数序列,找出其中出现次数最多的数。
输入格式
第一行包含整数n。
第二行包含n个整数,表示整数序列。
输出格式
输出一个整数,表示出现次数最多的数。
数据范围
1≤n≤100,
−109≤数列中的数≤109。
样例
输入样例:
6
10 1 10 20 30 20
输出样例:
10
算法1
(哈希表) $O(n)$
时间复杂度
参考文献
python3 代码
C++ 代码
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
### 回答2:
给定一个整数序列,求其中出现次数最多的数。
首先,我们需要遍历整个序列,统计每个数字出现的次数,可以使用一个哈希表来存储每个数字及其出现次数,然后在哈希表中找到出现次数最多的数字即可。
具体算法步骤如下:
1. 声明一个哈希表,将序列中的每个数字和其出现次数存储在哈希表中。
2. 遍历哈希表,找到出现次数最多的数字。
3. 如果存在多个出现次数相同的数字,返回其中任意一个即可。
以下是求解示例:
输入:1 2 3 4 5 2 3 4 2 3
输出:2
解释:数字 2 在序列中出现了 3 次,是出现次数最多的数字。
代码实现:
```
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, int> mp; // 声明哈希表,存储序列中每个数字及其出现次数
int n, maxVal = 0, res; // n表示序列长度,maxVal表示出现次数最多的数字出现的次数,res表示出现次数最多的数字
cin >> n; // 输入序列长度
for (int i = 0; i < n; i++) // 输入序列
{
int num;
cin >> num;
mp[num]++; // 统计每个数字出现的次数
if (mp[num] > maxVal) // 更新出现次数最多的数字
{
maxVal = mp[num];
res = num;
}
}
cout << res << endl; // 输出出现次数最多的数字
return 0;
}
```
时间复杂度分析:遍历序列的时间复杂度为 O(n),遍历哈希表的时间复杂度为 O(k),其中 k 表示哈希表中不同的数字个数,由于 k <= n,所以总时间复杂度为 O(n)。
因此,以上算法可以高效地解决出现次数最多的数字问题。
### 回答3:
这道题目要求我们在一个整数序列中找到出现次数最多的数。我们可以通过遍历整个序列,记录每个数字出现的次数,然后找出出现次数最多的数字即可。
具体地说,我们可以利用一个哈希表来记录每个数字出现的次数。遍历序列的过程中,对于每一个数字,我们可以检查它是否已经在哈希表中出现过,如果出现过,就把该数字对应的计数器加一;否则,就在哈希表中新增一项,把该数字的计数器初始化为 1。
最后,我们再次遍历整个哈希表,找到计数器最大的数字,即为出现次数最多的数。需要注意的是,如果序列中出现次数最多的数不止一个,我们需要全部输出。
总的时间复杂度为 O(n),其中 n 是序列的长度。以下是 Python 代码示例:
```python
def find_most_common_number(nums):
# 初始化哈希表
counts = {}
# 遍历整个序列,统计数字出现次数
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
# 找到出现次数最多的数字
max_count = 0
most_common_nums = []
for num in counts:
if counts[num] > max_count:
max_count = counts[num]
most_common_nums = [num]
elif counts[num] == max_count:
most_common_nums.append(num)
return most_common_nums
```
可以看到,这段代码非常简单,但是设计得非常巧妙,可以快速、准确地解决这道问题。需要注意的是,虽然我们使用了哈希表来加速计数过程,但是在最后一步找出出现次数最多的数字时,我们还是需要遍历整个哈希表,因此最坏的时间复杂度还是 O(n)。
阅读全文
相关推荐
















