mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
style: use getOrDefault
in MajorityElement
(#5454)
This commit is contained in:
@ -18,17 +18,13 @@ 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<>();
|
||||||
int n = nums.length;
|
for (final var num : nums) {
|
||||||
for (int i = 0; i < n; i++) {
|
final var curCount = numToCount.getOrDefault(num, 0);
|
||||||
if (numToCount.containsKey(nums[i])) {
|
numToCount.put(num, curCount + 1);
|
||||||
numToCount.put(nums[i], numToCount.get(nums[i]) + 1);
|
|
||||||
} else {
|
|
||||||
numToCount.put(nums[i], 1);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
List<Integer> majorityElements = new ArrayList<>();
|
List<Integer> majorityElements = new ArrayList<>();
|
||||||
for (final var entry : numToCount.entrySet()) {
|
for (final var entry : numToCount.entrySet()) {
|
||||||
if (entry.getValue() >= n / 2) {
|
if (entry.getValue() >= nums.length / 2) {
|
||||||
majorityElements.add(entry.getKey());
|
majorityElements.add(entry.getKey());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user