Skip to content

Commit 7bde152

Browse files
authored
style: use getOrDefault in MajorityElement (#5454)
1 parent 2f9f448 commit 7bde152

File tree

1 file changed

+4
-8
lines changed

1 file changed

+4
-8
lines changed

src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java

+4-8
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,13 @@ This method returns the majority element(s) in the given array of integers.
1818
*/
1919
public static List<Integer> majority(int[] nums) {
2020
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);
2824
}
2925
List<Integer> majorityElements = new ArrayList<>();
3026
for (final var entry : numToCount.entrySet()) {
31-
if (entry.getValue() >= n / 2) {
27+
if (entry.getValue() >= nums.length / 2) {
3228
majorityElements.add(entry.getKey());
3329
}
3430
}

0 commit comments

Comments
 (0)