File tree 1 file changed +4
-8
lines changed
src/main/java/com/thealgorithms/datastructures/hashmap/hashing
1 file changed +4
-8
lines changed Original file line number Diff line number Diff line change @@ -18,17 +18,13 @@ This method returns the majority element(s) in the given array of integers.
18
18
*/
19
19
public static List <Integer > majority (int [] nums ) {
20
20
HashMap <Integer , Integer > numToCount = new HashMap <>();
21
- int n = nums .length ;
22
- for (int i = 0 ; i < n ; i ++) {
23
- if (numToCount .containsKey (nums [i ])) {
24
- numToCount .put (nums [i ], numToCount .get (nums [i ]) + 1 );
25
- } else {
26
- numToCount .put (nums [i ], 1 );
27
- }
21
+ for (final var num : nums ) {
22
+ final var curCount = numToCount .getOrDefault (num , 0 );
23
+ numToCount .put (num , curCount + 1 );
28
24
}
29
25
List <Integer > majorityElements = new ArrayList <>();
30
26
for (final var entry : numToCount .entrySet ()) {
31
- if (entry .getValue () >= n / 2 ) {
27
+ if (entry .getValue () >= nums . length / 2 ) {
32
28
majorityElements .add (entry .getKey ());
33
29
}
34
30
}
You can’t perform that action at this time.
0 commit comments