在不到 O(n) 的时间内在 C++ 的有限范围数组中查找每个元素的频率
假设我们有一个整数数组。数组为 A,大小为 n。我们的任务是在不到 O(n) 的时间内找到数组中所有元素的频率。元素的大小必须小于一个值,比如说 M。这里我们将使用二分搜索方法。这里,如果终端元素不同,我们将递归地将数组分成两部分,如果它的两个终端元素相同,则表示数组中的所有元素都与已经排序过的数组相同。
示例
#include<iostream> #include<vector> using namespace std; void calculateFreq(int arr[], int left, int right, vector<int>& frequency) { if (arr[left] == arr[right]) frequency[arr[left]] += right - left + 1; else { int mid = (left + right) / 2; calculateFreq(arr, left, mid, frequency); calculateFreq(arr, mid + 1, right, frequency); } } void getAllFrequency(int arr[], int n) { vector<int> frequency(arr[n - 1] + 1, 0); calculateFreq(arr, 0, n - 1, frequency); for (int i = 0; i <= arr[n - 1]; i++) if (frequency[i] != 0) cout << "Frequency of element " << i << " is " << frequency[i] << endl; } int main() { int arr[] = { 10, 10, 10, 20, 30, 30, 50, 50, 80, 80, 80, 90, 90, 99 }; int n = sizeof(arr) / sizeof(arr[0]); getAllFrequency(arr, n); }
输出
Frequency of element 10 is 3 Frequency of element 20 is 1 Frequency of element 30 is 2 Frequency of element 50 is 2 Frequency of element 80 is 3 Frequency of element 90 is 2 Frequency of element 99 is 1
广告