728x90
https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
leetcode.com
가장 많이 나오는 원소 2개 가져오기 일반적으로 딕셔너리를 사용해 원소를 카운트하고 정렬하여 2개만 슬라이싱한다
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
d={}
for i in nums:
d.setdefault(i,0)
d[i]+=1
return list(map(lambda x:x[0],sorted(d.items(),key=lambda x:x[1])))[-k:]
'알고리즘 > leetcode' 카테고리의 다른 글
2259. Remove Digit From Number to Maximize Result (0) | 2023.05.27 |
---|---|
2260. Minimum Consecutive Cards to Pick Up (1) | 2023.05.26 |
24. Swap Nodes in Pairs - python (0) | 2023.05.19 |
1721. Swapping Nodes in a Linked List - python (0) | 2023.05.16 |
59. Spiral Matrix II - python (0) | 2023.05.10 |
댓글