C++程序:已知数组的平均数和中位数,求众数
平均数、中位数和众数是统计学的三个基本概念。这些量有助于理解给定数据的集中趋势和分布。在本文中,我们将学习如何在已知给定数组(与非分组数据相同)的平均数和中位数的情况下,找到众数,使用 C++ 语言。
问题陈述
给定一个数字数组,我们必须在 C++ 中找到已知平均数和中位数的众数。
示例
输入
[5, 15, 25, 35, 35, 40, 10]
平均数 = 20
中位数 = 25
输出
35
暴力求解方法
众数是出现频率最高的数值。我们可以遍历数组并返回频率最高的元素,但这需要 O(n) 的时间,因为我们必须遍历整个数组。
步骤
- 我们使用 无序映射 来查找每个元素的频率。
- 现在,我们存储每个元素的计数。
- 我们初始化两个变量,众数为数组的第一个元素,**最大计数**为 0。
- 我们循环遍历映射中的每个键值对。对于每个元素,如果其频率大于**最大计数**,则更新**最大计数**并将众数设置为当前元素。
- 最后,我们返回数组的众数。
代码实现
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Function to find the mode
int findMode(const vector < int > & arr, int n) {
unordered_map < int, int > mp;
for (int i = 0; i < n; i++) {
mp[arr[i]]++;
}
int mode = arr[0];
int maxCount = 0;
for (const auto & x: mp) {
int element = x.first;
int count = x.second;
if (count > maxCount) {
maxCount = count;
mode = element;
}
}
// Return the mode
return mode;
}
int main() {
vector < int > arr = {5,15,25,35,35,40,10};
int n = arr.size();
int mode = findMode(arr, n);
cout << "The Mode of the given dataset is: " << mode << endl;
return 0;
}
输出
The Mode of the given dataset is: 35
**时间复杂度:**O(n),因为我们使用映射来存储每个元素的频率。
**空间复杂度:**O(1),常数空间
优化方法
如果给定数组的平均数和中位数,那么我们可以简单地使用直接公式来查找数组的众数,而不是遍历整个数组。
根据公式
众数 = 3 × 中位数 − 2 × 平均数
如果给定数组的平均数和中位数,我们可以简单地使用上述公式来找到众数。
步骤
- 我们将定义一个函数来查找给定数组的众数。
- 此函数将接收两个参数,平均数和中位数,并使用直接公式查找众数。
- 我们可以使用直接公式计算众数:众数 = 3 × 中位数 − 2 × 平均数。
代码实现
#include <iostream>
using namespace std;
// Function to calculate mode
double calculateMode(double mean, double median) {
return 3 * median - 2 * mean;
}
int main() {
double mean, median;
// Input mean and median
cout << "Enter the mean of the array: ";
cin >> mean;
cout << "Enter the median of the array: ";
cin >> median;
// Calculate mode using the formula
double mode = calculateMode(mean, median);
// Output the result
cout << "The mode of the array is: " << mode << endl;
return 0;
}
输出
Enter the mean of the array: 10 Enter the median of the array: 15 The mode of the array is: 25
**时间复杂度:**O(1),我们使用常数空间。
**空间复杂度:**O(1),因为没有使用额外的内存。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP