Now Access to Gemini (Google) : Really beat to ChatGPT ?

Most Frequent Even Element weekly contest [leetcode]

2404. Most Frequent Even Element weekly -310 leetcode contest.

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. 



Code : 

class Solution {
    public int mostFrequentEven(int[] nums) {
        // Arrays.sort(nums);
        int count = Integer.MIN_VALUE; 
        int number = -1 ;
        HashMap<Integer,Integer> store = new HashMap<Integer,Integer>();
        for(int i =0 ; i < nums.length ; i++){
            if(nums[i] % 2 == 0){
            store.put(nums[i], store.getOrDefault(nums[i],0)+1);
            }
        }
        // System.out.println(store);
        TreeMap<Integer,Integer> store1 = new TreeMap<>(store);
        for(Integer i : store1.keySet()){
            if(store.get(i)  > count){
                count = store.get(i);
                number = i;
            }
        }
        return number;
    }
}   

Join Telegram channel: Join Now 

Comments