프로그래밍/C++
C++ ] leetCode 3005 - Count Elements With Maximum Frequency
eteo
2024. 4. 16. 22:02
리트코드 3005 문제
You are given an array nums consisting of positive integers.
Return the total frequencies of elements in nums such that those elements all have the maximum frequency.
The frequency of an element is the number of occurrences of that element in the array.
Example 1:
- Input: nums = [1,2,2,3,1,4]
- Output: 4
- Explanation: The elements 1 and 2 have a frequency of 2 which is the maximum frequency in the array. So the number of elements in the array with maximum frequency is 4.
Example 2:
- Input: nums = [1,2,3,4,5]
- Output: 5
- Explanation: All elements of the array have a frequency of 1 which is the maximum. So the number of elements in the array with maximum frequency is 5.
Constraints:
- 1 <= nums.length <= 100
- 1 <= nums[i] <= 100
unordered_map에 num과 등장빈도를 저장하고 max값을 확인해둔다. value가 max인 키의 개수 * max가 답이고 map을 순회탐색해 구할 수 있다.
class Solution {
public:
int maxFrequencyElements(vector<int>& nums) {
unordered_map<int, int> um;
int max = 0, ret = 0;
for(int i = 0; i < nums.size(); i++) {
um[nums[i]]++;
max = um[nums[i]] > max ? um[nums[i]] : max;
}
for(auto& pair : um) {
if(pair.second == max) {
ret += max;
}
}
return ret;
}
};