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),因為沒有使用額外的記憶體。

更新於: 2024年11月10日

76 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告