6 lines in Python


  • 0
    L
        def topKFrequent(self, words, k):
            """
            :type words: List[str]
            :type k: int
            :rtype: List[str]
            """
    
            m = collections.defaultdict(int)
            for word in words:
                m[word] += 1
    
    
            m_sorted = sorted(m.items(),key=lambda x:(-x[1], x[0]))
            first_k = m_sorted[:k]
            return [first for first, _ in first_k]
            
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.