動機

medium!?

Problem

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 = 2Output: [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 = 4Output: [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.

Sol

兩個hash去對

  • string => 次數
  • 次數 => [string]

BTW,from collections import Counter 可以計算 string => 次數

class Solution:
    def topKFrequent(self, ws: List[str], kk: int) -> List[str]:
        w_t = {}
        t_ws = {}
        
        for w in ws:
            if w not in w_t:
                w_t[w] = 1
            else:
                w_t[w] += 1
        
        for (k,v) in w_t.items():
            if v not in t_ws:
                t_ws[v] = [k]
            else:
                t_ws[v].append(k)
        
        t_iter = iter(sorted(t_ws.keys(),reverse=True))
        ret = []
        while kk != 0:
            t = next(t_iter)
            if kk < len(t_ws[t]):
                ret += sorted(t_ws[t])[:kk]
                kk = 0
            elif kk == len(t_ws[t]):
                ret += sorted(t_ws[t])
                kk = 0
            else:
                ret += sorted(t_ws[t])
                kk -= len(t_ws[t])
        return ret