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.
반응형
'python-algorithm' 카테고리의 다른 글
leetcode 1684. Count the Number of Consistent Strings (2) | 2023.01.22 |
---|---|
leetcode 58. Length of Last Word (0) | 2023.01.21 |
leetcode 2465. Number of Distinct Averages (0) | 2023.01.19 |
leetcode 2496. Maximum Value of a String in an Array (0) | 2023.01.19 |
leetcode 2535. Difference Between Element Sum and Digit Sum of an Array (0) | 2023.01.17 |
댓글