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 | 31 |
Tags
- gs25
- leetcode
- Kaggle
- Docker
- 파이썬
- 캐치카페
- 프로그래머스 파이썬
- 편스토랑 우승상품
- Git
- 자연어처리
- Real or Not? NLP with Disaster Tweets
- 우분투
- AI 경진대회
- PYTHON
- 더현대서울 맛집
- 프로그래머스
- ChatGPT
- SW Expert Academy
- ubuntu
- 금융문자분석경진대회
- programmers
- 백준
- 데이콘
- hackerrank
- github
- Baekjoon
- 편스토랑
- dacon
- 코로나19
- 맥북
Archives
- Today
- Total
솜씨좋은장씨
[leetCode] 692. Top K Frequent Words (Python) 본문
728x90
반응형
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
with the number of occurrence being 4, 3, 2 and 1 respectively.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- Try to solve it in O(n log k) time and O(n) extra space.
Solution
from collections import Counter
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
cnt = Counter(words)
print(cnt.items())
most_list = sorted(list(cnt.items()), key=lambda x: [-x[1], x[0]])
print(most_list)
answer = []
for i in range(k):
answer.append(most_list[i][0])
return answer
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[leetCode] 1154. Day of the Year (Python) (0) | 2020.07.25 |
---|---|
[leetCode] 342. Power of Four (Python) (0) | 2020.07.24 |
[leetCode] 386. Lexicographical Numbers (Python) (0) | 2020.07.22 |
[leetCode] 172. Factorial Trailing Zeroes (Python) (0) | 2020.07.21 |
[leetCode] 137. Single Number II (Python) (2) | 2020.07.20 |
Comments