在 C++ 中查詢排序陣列中頻率大於或等於 n/2 的元素。
假設我們有一個大小為 n 的陣列。此陣列已排序。有一個元素的頻率大於或等於 n/2,其中 n 是陣列中元素的數量。所以如果陣列類似於 [3, 4, 5, 5, 5],則輸出將為 5。
如果我們仔細觀察這些型別的陣列,我們可以很容易地注意到頻率大於或等於 n/2 的數字也存在於索引 n/2 處。因此,該元素可以在位置 n/2 找到。
示例
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";
}輸出 -
The number 4 has occurred more than or equal to 10/2 amount of times
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP