관리 메뉴

솜씨좋은장씨

[leetCode] 692. Top K Frequent Words (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 692. Top K Frequent Words (Python)

사용자 솜씨좋은장씨 2020. 7. 23. 02:18
반응형

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:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

Follow up:

  1. 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

반응형
0 Comments
댓글쓰기 폼