package com.算法专练.力扣.最大相等频率;
/**
* @author xnl
* @Description:
* @date: 2022/8/18 22:10
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {2,2,1,1,5,3,3,5};
System.out.println(solution.maxEqualFreq(nums));
}
// 每个数出现的个数
int[] cnt = new int[100010];
// 出现次数为 i 的值有多少个
int[] sum = new int[100010];
public int maxEqualFreq(int[] nums) {
int n = nums.length, max = 0, ans = 0;
for (int i = 0; i < n; i++){
// 首先记录出现的个数,并且记录数组的长度
int t = nums[i], cur = ++cnt[t], len = i + 1;
sum[cur]++;
// 注意,因为出现的次数加一了,那个上一个状态下出现的次数就应该减一。这样状态才能继续下去
sum[cur - 1]--;
max = Math.max(max, cur);
if (max == 1){
ans = len;
}
if (max * sum[max] + 1 == len){
ans = len;
}
if ((max - 1) * (sum[max - 1] + 1) + 1 == len){
ans = len;
}
}
return ans;
}
}
力扣:1224. 最大相等频率
最新推荐文章于 2024-06-22 22:59:06 发布