Given an array nums
of positive integers, return the longest possible length of an array prefix of nums
, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
Example 1:
Input: nums = [2,2,1,1,5,3,3,5] Output: 7 Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5] Output: 13
Example 3:
Input: nums = [1,1,1,2,2,2] Output: 5
Example 4:
Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6] Output: 8
Constraints:
2 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
题目链接:https://leetcode.com/problems/maximum-equal-frequency/
题目大意:给一个数组,求一个最长的前缀,使得该前缀删除一个数字后其余数字频数相同
题目分析:这题是hard。。。?cnt数组记录数字出现次数,freq数组记录cnt的频数,如果满足条件必然只有两种情况:
一.待删除数字在当前前缀中,比如1 1 3 2 2
二.当前前缀满足频数要求,需删除后面的数字,比如1 1 2 2 3
分别判断下即可
5ms,时间击败95%
class Solution {
public int maxEqualFreq(int[] nums) {
int[] cnt = new int[100005];
int[] freq = new int[100005];
int ans = 1, n = nums.length;
for (int i = 0; i < n; i++) {
cnt[nums[i]]++;
int numCount = cnt[nums[i]];
freq[numCount]++;
// System.out.println("freq[" + numCount + "] = " + freq[numCount] + " i = " + i);
if (freq[numCount] * numCount == i) {
ans = Math.max(ans, i + 1);
} else if (freq[numCount] * numCount == i + 1 && i < n - 1) {
ans = Math.max(ans, i + 2);
}
}
return ans;
}
}