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
Solution: Hashtable
Use a hashtable to store the frequency of each element, and compare it with a running maximum frequency. Reset answer if current frequency is greater than maximum frequency. Increment the answer if current frequency is equal to the maximum frequency.
Time complexity: O(n)
Space complexity: O(n)
C++
// Author: Huahua
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Solution { public: int maxFrequencyElements(vector<int>& nums) { unordered_map<int, int> m; int freq = 0; int ans = 0; for (int x : nums) { if (++m[x] > freq) freq = m[x], ans = 0; if (m[x] == freq) ans += m[x]; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment