347. Top K Frequent Elements QuestionEditorial Solution My Submissions
Total Accepted: 28149
Total Submissions: 63972
Difficulty: Medium
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 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.
def topKFrequent(self, nums, k): """ All elements in the nums array can be a candidate of the final outputs. We use the dictionary candidates to count the number of appearance of candidates. """ count_qualified = 0 # number of qualified candidates # the initial value is obviously 0. level = 0 # if candidates[n] > level the n is qualified candidates = {} for n in nums: candidates[n] = candidates.get(n,0) + 1 # add 1 to the count if candidates[n] == level + 1:
# this is the only case we care. If candidates[n] <= offset,
# then n is not qualified and no impact on the count_effect # for candidates[n] > offset + 1, it means that n has been
# already counted as qualified. So no impact neither count_qualified += 1 # add 1 more qualified candidate if count_qualified > k:
# if the number of quanlified candidates is greater than
# the target, we will increase the level of qualification level += 1 for item in candidates.values():# update the count_quanlified if item == level: count_qualified -= 1 res = [key for key,val in candidates.items() if val > level] return res