-
99클럽 코테 스터디 11일차 TIL: 배열, Leetcode 347. Top K Frequent ElementsToday_I_Learned/Algorithm 2024. 6. 20. 23:00
문제
https://leetcode.com/problems/top-k-frequent-elements/description/
통과 여부
Fail -> Pass
나의 접근법
- num 를 순회하며 각 element 의 count 를 별도의 dict 에 count:[num,..] 으로 저장
- dict 의 key 로 정렬하려 앞에서부터 k까지의 key 에 속하는 value(숫자) 를 Return
... 이라는 거창한 계획을 세웠었는데
항해 정규 스터디 시간을 통해 python 의 collections 에서 most_common() 이라는 함수를 제공하고 있다는 사실을 알게 되었다. 이 함수를 사용하면 1 줄 coding 이 가능해진다!!!
python 을 이런 utility 함수들이 많이 제공되고 있다보니 배열같은 문제에서 더 강한 것 같다.
import collections class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: return [k for k, v in collections.Counter(nums).most_common(k)]
'Today_I_Learned > Algorithm' 카테고리의 다른 글
99클럽 코테 스터디 13일차 TIL: 스택/큐, Leetcode 1823. Find the Winner of the Circular Game (0) 2024.06.22 99클럽 코테 스터디 12일차 TIL: 정렬, Leetcode 869. Reordered Power of 2 (0) 2024.06.21 99클럽 코테 스터디 10일차 TIL: 배열, Leetcode 451. Sort Characters By Frequency (0) 2024.06.19 99클럽 코테 스터디 9일차 TIL: 배열, 1529. Minimum Suffix Flips (0) 2024.06.19 99클럽 코테 스터디 8일차 TIL: 배열, 1286. Iterator for Combination (0) 2024.06.18