"""Leetcode 347. Top K Frequent Elements

URL: https://leetcode.com/problems/top-k-frequent-elements/

Medium

Given a non-empty array of integers, return the k most frequent elements.

Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:
Input: nums = [1], k = 1
Output: [1]

Note:
You may assume k is always valid, 1 <= k <= number of unique elements.
Your algorithm's time complexity must be better than O(n log n),
where n is the array's size.
"""

class Solution(object):
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        freq_d = {}

        for n in nums:
            if n in freq_d:
                freq_d[n] += 1
            else:
                freq_d[n] = 1
                
        sorted_freq_ls = sorted(
            freq_d.items(), key=lambda x: x[1], reverse=True)
        topk_ls = [t[0] for t in sorted_freq_ls[:k]]
        return topk_ls


def main():
    nums = [1, 1, 1, 2, 2, 3]
    k = 2
    # Output: [1,2]
    print Solution().topKFrequent(nums, k)

    nums = [1]
    k = 1
    # Output: [1]
    print Solution().topKFrequent(nums, k)

    nums = [3,2,3,1,2,4,5,5,6,7,7,8,2,3,1,1,1,10,11,5,6,2,4,7,8,5,6]
    k = 10
    # Output: [1,2,5,3,7,6,4,8,10,11]
    print Solution().topKFrequent(nums, k)


if __name__ == '__main__':
    main()

@@ -631,24 +631,28 @@
 %22%22%22%0A        
+num_
 freq_d = %7B%7D%0A
@@ -695,16 +695,20 @@
 if n in 
+num_
 freq_d:%0A
@@ -715,32 +715,36 @@
                 
+num_
 freq_d%5Bn%5D += 1%0A 
@@ -772,24 +772,28 @@
             
+num_
 freq_d%5Bn%5D = 
@@ -822,24 +822,28 @@
      sorted_
+num_
 freq_ls = so
@@ -847,29 +847,20 @@
  sorted(
-%0A            
+num_
 freq_d.i
@@ -870,28 +870,100 @@
 s(),
- key=lambda x: x%5B1%5D,
+%0A                                    key=lambda x: x%5B1%5D,%0A                                   
  rev
@@ -990,24 +990,35 @@
 opk_
-l
+num
 s = %5B
-t%5B0%5D
+num
  for 
-t
+(num, freq)
  in 
@@ -1024,16 +1024,20 @@
  sorted_
+num_
 freq_ls%5B
@@ -1061,17 +1061,19 @@
 rn topk_
-l
+num
 s%0A%0A%0Adef 
@@ -1122,30 +1122,33 @@
 k = 2%0A    # 
-Output
+Should be
 : %5B1,2%5D%0A    
@@ -1214,30 +1214,33 @@
 k = 1%0A    # 
-Output
+Should be
 : %5B1%5D%0A    pr
@@ -1363,22 +1363,25 @@
 0%0A    # 
-Output
+Should be
 : %5B1,2,5

Revise var naming for clarification