Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- PYTHON
- Real or Not? NLP with Disaster Tweets
- Git
- 파이썬
- Docker
- github
- ubuntu
- 백준
- hackerrank
- 편스토랑 우승상품
- 우분투
- 코로나19
- programmers
- dacon
- 편스토랑
- SW Expert Academy
- AI 경진대회
- Kaggle
- 맥북
- 프로그래머스
- 프로그래머스 파이썬
- gs25
- 더현대서울 맛집
- leetcode
- 금융문자분석경진대회
- Baekjoon
- 데이콘
- 캐치카페
- ChatGPT
- 자연어처리
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 347. Top K Frequent Elements (Python) 본문
728x90
반응형

Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
- It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
- You can return the answer in any order.
Solution
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
cnt = Counter(nums)
most_common_k = cnt.most_common(k)
answer = [num[0] for num in most_common_k]
return answer



SOMJANG/CODINGTEST_PRACTICE
1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.
github.com
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[leetCode] 451. Sort Characters By Frequency (Python) (0) | 2020.10.20 |
---|---|
[leetCode] 215. Kth Largest Element in an Array (Python) (0) | 2020.10.19 |
[leetCode] 442. Find All Duplicates in an Array (Python) (0) | 2020.10.13 |
[leetCode] 504. Base 7 (Python) (0) | 2020.10.12 |
[leetCode] 1470. Shuffle the Array (Python) (0) | 2020.10.10 |