元素在 C++ 排序陣列中出現超過 25%
假設我們有一個數組 A。有一些元素。有些元素是常見的。我們必須返回一個在陣列中出現超過 25% 的元素。因此,如果 A = [1, 2, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7],則 4 出現了四次。這超過了 12(陣列的大小)的 25%
要解決此問題,我們將遵循以下步驟 -
- 讀取元素並存儲其各自的頻率
- 如果頻率大於陣列大小的 25%,則返回結果。
示例
讓我們看以下實現以獲得更好的理解 -
#include <bits/stdc++.h> using namespace std; class Solution { public: int findSpecialInteger(vector<int>& arr) { int n = arr.size(); int req = n / 4; unordered_map <int, int> m; int ans = -1; for(int i = 0; i < n; i++){ m[arr[i]]++; if(m[arr[i]] > req)ans = arr[i]; } return ans; } }; main(){ Solution ob; vector<int> c = {1,2,4,4,4,4,5,5,6,6,7,7}; cout << ob.findSpecialInteger(c); }
輸入
[1,2,4,4,4,4,5,5,6,6,7,7]
輸出
4
廣告