style: use getOrDefault in MajorityElement (#5455)

This commit is contained in:
Piotr Idzik
2024-09-19 17:49:28 +02:00
committed by GitHub
parent 7bde1523a5
commit e782c7ac3d

View File

@ -19,8 +19,7 @@ public final class MajorityElement {
public static List<Integer> majority(int[] nums) { public static List<Integer> majority(int[] nums) {
HashMap<Integer, Integer> numToCount = new HashMap<>(); HashMap<Integer, Integer> numToCount = new HashMap<>();
for (final var num : nums) { for (final var num : nums) {
final var curCount = numToCount.getOrDefault(num, 0); numToCount.merge(num, 1, Integer::sum);
numToCount.put(num, curCount + 1);
} }
List<Integer> majorityElements = new ArrayList<>(); List<Integer> majorityElements = new ArrayList<>();
for (final var entry : numToCount.entrySet()) { for (final var entry : numToCount.entrySet()) {