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

Tìm phần tử trong mảng đã sắp xếp có tần suất lớn hơn hoặc bằng n/2 trong C++


Xét mảng kích thước n, đã sắp xếp. Có một phần tử xuất hiện với tần suất lớn hơn hoặc bằng n/2. Ví dụ mảng [3, 4, 5, 5, 5] thì kết quả là 5.

Quan sát kỹ, phần tử có tần suất ≥ n/2 sẽ nằm ở chỉ số n/2. Do đó phần tử đó chính là arr[n/2].

Ví dụ

Source Code: #include<iostream> using namespace std; int higherFreq(int arr[], int n) {    return arr[n / 2]; } int main() {    int arr[] = { 1, 2, 3, 4 , 4, 4, 4, 4, 4, 5};    int n = sizeof(arr) / sizeof(arr[0]);    cout << "The number " << higherFreq(arr, n) << " has occurred more than or equal to "<<n <<"/2 amount of times"; }

Kết quả

The number 4 has occurred more than or equal to 10/2 amount of times