Op K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume K are 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.
The number of K with the highest frequency is required and the time complexity must not exceed O (n log n).
Choose the simplest fast row O (n log n) to solve, first find out the probability of each number, and then the order to find the results.
The sort of place with a lambda function is an anonymous method, if it is ascending, written as:
List.sort (Key=lambda x:x[1])
Equivalent:
List.sort (Lambda a,b:cmp (a[1],b[1]))
1 classsolution (object):2 deftopkfrequent (self, nums, K):3 """4 : Type Nums:list[int]5 : Type K:int6 : Rtype:list[int]7 """8Self.__dict= {}; list = []; res = []9 forIteminchNums:Ten ifSelf.__dict. Has_key (item): OneSelf.__dict[item] + = 1 A Else: -Self.__dict[Item] = 1 - forIteminchSelf.__dict: theList.append (item, self.__dict[item])) -List.sort (key=LambdaX:-x[1]) - forIinchRange (k): - res.append (list[i][0]) + returnRes
[Leetcode] [Python] Top K Frequent Elements