All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g2401_2500.s2404_most_frequent_even_element.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g2401_2500.s2404_most_frequent_even_element;

// #Easy #Array #Hash_Table #Counting #2022_10_23_Time_32_ms_(81.60%)_Space_56.5_MB_(79.42%)

import java.util.HashMap;
import java.util.Map;

/**
 * 2404 - Most Frequent Even Element\.
 *
 * Easy
 *
 * Given an integer array `nums`, return _the most frequent even element_.
 *
 * If there is a tie, return the **smallest** one. If there is no such element, return `-1`.
 *
 * **Example 1:**
 *
 * **Input:** nums = [0,1,2,2,4,4,1]
 *
 * **Output:** 2
 *
 * **Explanation:**
 *
 * The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
 *
 * We return the smallest one, which is 2.
 *
 * **Example 2:**
 *
 * **Input:** nums = [4,4,4,9,2,4]
 *
 * **Output:** 4
 *
 * **Explanation:** 4 is the even element appears the most. 
 *
 * **Example 3:**
 *
 * **Input:** nums = [29,47,21,41,13,37,25,7]
 *
 * **Output:** -1
 *
 * **Explanation:** There is no even element. 
 *
 * **Constraints:**
 *
 * *   `1 <= nums.length <= 2000`
 * *   0 <= nums[i] <= 105
**/
public class Solution {
    public int mostFrequentEven(int[] nums) {
        Map frequencyMap = new HashMap<>();
        int mostFrequent = Integer.MAX_VALUE;
        int maxFrequency = 0;
        for (int num : nums) {
            if ((num & 1) == 0) {
                maxFrequency =
                        Math.max(
                                maxFrequency,
                                frequencyMap.compute(num, (n, freq) -> freq == null ? 1 : ++freq));
            }
        }
        for (Map.Entry entry : frequencyMap.entrySet()) {
            if (entry.getValue() == maxFrequency) {
                mostFrequent = Math.min(mostFrequent, entry.getKey());
            }
        }
        return mostFrequent == Integer.MAX_VALUE ? -1 : mostFrequent;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy