最大频率元素计数
难度:
标签:
题目描述
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
代码结果
运行时间: 22 ms, 内存: 16.0 MB
/*
* 思路:
* 1. 使用流式操作统计每个元素的频率。
* 2. 找到最大频率。
* 3. 计算具有最大频率的元素的总数量。
*/
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Solution {
public int findMaxFrequencyCount(int[] nums) {
// 统计每个元素的频率
Map<Integer, Long> frequencyMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// 找到最大频率
long maxFrequency = frequencyMap.values().stream()
.max(Long::compare)
.orElse(0L);
// 计算具有最大频率的元素的总数量
long maxFrequencyCount = frequencyMap.values().stream()
.filter(frequency -> frequency == maxFrequency)
.mapToLong(Long::longValue)
.sum();
return (int) maxFrequencyCount;
}
}
解释
方法:
本题解首先使用了Counter来统计数组nums中每个元素的频率,存储在字典ds中。接着,通过遍历ds的值找到最大频率maxN。然后,再次遍历ds,统计所有频率等于maxN的元素的频率总和,这一总和即为所有具有最大频率的元素在数组中出现的次数。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
在使用Counter来统计每个元素的频率后,你是如何确保找到的最大频率真正代表了数组中出现最频繁的元素?
▷🦆
在计算最大频率maxN时,为什么选择使用生成器表达式而不是直接对Counter对象调用max函数?
▷🦆
题解中再次遍历字典来统计答案时,是否有更高效的方法来同时获得最大频率及其对应的元素总数,以减少遍历次数?
▷🦆
在处理边界情况,比如数组中每个元素都是唯一的,或者所有元素都是相同的情况下,这种算法的性能表现如何?
▷