Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Element Appearing More Than 25% In Sorted Array in C++
Suppose we have an array A. There are few elements. Some elements are common. We have to return an element that is appearing more than 25% spaces in the array. So if A = [1, 2, 4, 4, 4, 4, 5, 5, 6, 6, 7, 7], Here 4 has occurred four times. This is more than 25% of 12 (size of the array)
To solve this, we will follow these steps −
- Read elements and store their respective frequencies
- If the frequency is greater than 25% of the array size, then return the result.
Example
Let us see the following implementation to get better understanding −
#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);
}
Input
[1,2,4,4,4,4,5,5,6,6,7,7]
Output
4
Advertisements