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
- gs25
- dacon
- 캐치카페
- programmers
- 프로그래머스
- Baekjoon
- hackerrank
- 맥북
- 데이콘
- Real or Not? NLP with Disaster Tweets
- PYTHON
- github
- 프로그래머스 파이썬
- 우분투
- ChatGPT
- SW Expert Academy
- 코로나19
- 금융문자분석경진대회
- leetcode
- AI 경진대회
- Kaggle
- 자연어처리
- Docker
- 백준
- 편스토랑 우승상품
- 더현대서울 맛집
- ubuntu
- Git
- 편스토랑
- 파이썬
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
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] 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