Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Phần tử xuất hiện nhiều nhất trong mảng C++

Tìm phần tử có tần suất xuất hiện lớn nhất trong mảng.

Ví dụ

Input: [1, 2, 3, 3, 2, 2, 1, 1, 2, 3, 4]
Output: 2 (xuất hiện 4 lần)

Cách 1: Hash Map (O(N))

  • Dùng unordered_map đếm tần suất.
  • Duyệt map tìm key có value lớn nhất.

Cách 2: Sắp xếp (O(N log N))

  • Sắp xếp mảng.
  • Duyệt đếm độ dài dãy liên tiếp giống nhau.

Triển khai C++ (Hash Map)

#include <bits/stdc++.h>
using namespace std;

int mostFrequent(int arr[], int n) {
    unordered_map freq;
    for (int i = 0; i < n; i++) freq[arr[i]]++;

    int maxCount = 0, res = -1;
    for (auto& p : freq)
        if (p.second > maxCount) { maxCount = p.second; res = p.first; }
    return res;
}

int main() {
    int arr[] = {1,2,3,3,2,2,1,1,2,3,4};
    cout << mostFrequent(arr, 11) << endl; // 2
    return 0;
}

Kết quả

2