LeetCode 2404. Most Frequent Even Element Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2404. Most Frequent Even Element

Description

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

Solutions

Solution 1: Hash Table

We use a hash table cnt to count the occurrence of all even elements, and then find the even element with the highest occurrence and the smallest value.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array.

PythonJavaC++GoTypeScriptRustPHP
class Solution: def mostFrequentEven(self, nums: List[int]) -> int: cnt = Counter(x for x in nums if x % 2 == 0) ans, mx = -1, 0 for x, v in cnt.items(): if v > mx or (v == mx and ans > x): ans, mx = x, v return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !