1
- class Solution {
2
- private static int [] cnt = new int [100010 ];
3
- private static int [] ccnt = new int [100010 ];
1
+ import java .util .HashMap ;
2
+ import java .util .Map ;
4
3
4
+ class Solution {
5
5
public int maxEqualFreq (int [] nums ) {
6
- Arrays .fill (cnt , 0 );
7
- Arrays .fill (ccnt , 0 );
8
- int ans = 0 ;
9
- int mx = 0 ;
10
- for (int i = 1 ; i <= nums .length ; ++i ) {
11
- int v = nums [i - 1 ];
12
- if (cnt [v ] > 0 ) {
13
- --ccnt [cnt [v ]];
6
+ Map <Integer , Integer > count = new HashMap <>(); // Use HashMap to store the frequency of each number
7
+ Map <Integer , Integer > freqCount = new HashMap <>(); // Use HashMap to store the frequency of each frequency
8
+ int maxFreq = 0 , ans = 0 ;
9
+ for (int i = 0 ; i < nums .length ; i ++) {
10
+ int num = nums [i ];
11
+ if (count .containsKey (num )) {
12
+ freqCount .put (count .get (num ), freqCount .getOrDefault (count .get (num ), 0 ) - 1 ); // Decrement the count of the previous frequency
14
13
}
15
- ++cnt [v ];
16
- mx = Math .max (mx , cnt [v ]);
17
- ++ccnt [cnt [v ]];
18
- if (mx == 1 ) {
19
- ans = i ;
20
- } else if (ccnt [mx ] * mx + ccnt [mx - 1 ] * (mx - 1 ) == i && ccnt [mx ] == 1 ) {
21
- ans = i ;
22
- } else if (ccnt [mx ] * mx + 1 == i && ccnt [1 ] == 1 ) {
23
- ans = i ;
14
+ count .put (num , count .getOrDefault (num , 0 ) + 1 ); // Increment the count of the current number
15
+ maxFreq = Math .max (maxFreq , count .get (num )); // Update the maximum frequency
16
+ freqCount .put (count .get (num ), freqCount .getOrDefault (count .get (num ), 0 ) + 1 ); // Increment the count of the current frequency
17
+
18
+ if (maxFreq == 1 ) {
19
+ ans = i + 1 ; // Update the answer if all elements have the same frequency (1)
20
+ } else if (freqCount .get (maxFreq ) * maxFreq + (freqCount .getOrDefault (maxFreq - 1 , 0 ) * (maxFreq - 1 )) == i + 1 && freqCount .get (maxFreq ) == 1 ) {
21
+ ans = i + 1 ; // Update the answer if there's only one element with the maximum frequency and all other elements have a frequency one less than the maximum
22
+ } else if (freqCount .get (maxFreq ) * maxFreq + 1 == i + 1 && freqCount .get (1 ) == 1 ) {
23
+ ans = i + 1 ; // Update the answer if there's only one element with a frequency of 1 and all other elements have the maximum frequency
24
24
}
25
25
}
26
26
return ans ;
27
27
}
28
- }
28
+ }
0 commit comments