본문 바로가기
python-algorithm

leetcode 2404. Most Frequent Even Element

by 무적김두칠 2023. 1. 19.

https://leetcode.com/problems/most-frequent-even-element/description/

 

Most Frequent Even Element - LeetCode

Most Frequent Even Element - 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

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
from collections import Counter
class Solution:
    def mostFrequentEven(self, nums: List[int]) -> int:
        answer = -1
        sorted_nums = sorted(Counter(nums).most_common(), key= lambda x:(-x[1],x[0]) )
        for i in sorted_nums:
            if i[0] % 2 == 0:
                answer = i[0]
                return answer
        return answer
        
cs

1. Counter를 이용해서 가장 빈도가 큰 숫자를 찾고
2. 정렬 후 조건에 맞는 값을 return 하면 됩니다.

1. Use Counter to find the number with the highest frequency
2. After sorting, return the value that meets the condition.

반응형

댓글