Skip to content

Commit

Permalink
style: use getOrDefault in MajorityElement (#5454)
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Sep 18, 2024
1 parent 2f9f448 commit 7bde152
Showing 1 changed file with 4 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,13 @@ This method returns the majority element(s) in the given array of integers.
*/
public static List<Integer> majority(int[] nums) {
HashMap<Integer, Integer> numToCount = new HashMap<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
if (numToCount.containsKey(nums[i])) {
numToCount.put(nums[i], numToCount.get(nums[i]) + 1);
} else {
numToCount.put(nums[i], 1);
}
for (final var num : nums) {
final var curCount = numToCount.getOrDefault(num, 0);
numToCount.put(num, curCount + 1);
}
List<Integer> majorityElements = new ArrayList<>();
for (final var entry : numToCount.entrySet()) {
if (entry.getValue() >= n / 2) {
if (entry.getValue() >= nums.length / 2) {
majorityElements.add(entry.getKey());
}
}
Expand Down

0 comments on commit 7bde152

Please sign in to comment.