@@ -0,0 +1,2575 @@
+# Top K Frequent Words%0A# Challange%0A%0A%22%22%22%0AI threw myself at this one, not really any time to %22study%22%0A the solution was stupid simple in hind sight.  It took only 5 lines of code to solve this riddle.%0A%0AGiven a non-empty list of words, return the k most frequent elements.%0A%0AYour 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.%0A%0AExample 1:%0AInput: %5B%22i%22, %22love%22, %22leetcode%22, %22i%22, %22love%22, %22coding%22%5D, k = 2%0AOutput: %5B%22i%22, %22love%22%5D%0AExplanation: %22i%22 and %22love%22 are the two most frequent words.%0A    Note that %22i%22 comes before %22love%22 due to a lower alphabetical order.%0A%0AExample 2:%0AInput: %5B%22the%22, %22day%22, %22is%22, %22sunny%22, %22the%22, %22the%22, %22the%22, %22sunny%22, %22is%22, %22is%22%5D, k = 4%0AOutput: %5B%22the%22, %22is%22, %22sunny%22, %22day%22%5D%0AExplanation: %22the%22, %22is%22, %22sunny%22 and %22day%22 are the four most frequent words,%0A    with the number of occurrence being 4, 3, 2 and 1 respectively.%0A%0ANote:%0AYou may assume k is always valid, 1 %E2%89%A4 k %E2%89%A4 number of unique elements.%0AInput words contain only lowercase letters.%0A%0AFollow up:%0ATry to solve it in O(n log k) time and O(n) extra space.%0A%0ACode Break Down%0A%0Aclass Solution:%0A    def topKFrequent(self, words, k):%0A        %22%22%22%0A        :type words: List%5Bstr%5D%0A        :type k: int%0A        :rtype: List%5Bstr%5D%0A        %22%22%22%0A%0AWhen I found this snippet, it was basically the whole solution.%0A%0ABut there are two ways of doing this, through sorting and through        %0A%22%22%22%0AApproach #1: Sorting %5BAccepted%5D%0AIntuition and Algorithm%0A%0A%0A%0APython%0A%0A# Sorting%0A# Count the frequency of each word, and sort the words with a custom %0A# ordering relation that uses these frequencies. Then take the best k of # them.%0A%0A    def topKFrequent(words, k):%0A        count = collections.Counter(words)%0A        candidates = count.keys()%0A        candidates.sort(key = lambda w: (-count%5Bw%5D, w))%0A        return candidates%5B:k%5D%0A%0A%0A# Heaping%0A# Count the frequency of each word, then add it to heap that stores the%0A# best k candidates. Here, %22best%22 is defined with our custom ordering %0A# relation, which puts the worst candidates at the top of the heap. At%0A# the end, we pop off the heap up to k times and reverse the result so%0A# that the best candidates are first.%0A%0A# Pro Python Tip%0A# In Python, we instead use heapq.heapify, which can turn a list into a # heap in linear time, simplifying our work.%0A%0A    def topKFrequent(words, k):%0A        count = collections.Counter(words)%0A        heap = %5B(-freq, word) for word, freq in count.items()%5D%0A        heapq.heapify(heap)%0A        return %5Bheapq.heappop(heap)%5B1%5D for _ in xrange(k)%5D%0A

Create topk.py