在 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

更新於: 2019-12-19

115 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.