Top K Frequent Elements Explaination
Table of Contents
1. Explanation
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
1.1. Example:
Input: nums = [1,1,1,2,2,3]; k = 2 Output: [1,2]
1.2. Constraints:
1 <= nums.length <= 105 -104 <= nums[i] <= 104
k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique.
1.3. Follow up:
Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.
2. My Method
nums = [3,6,3,5,6,5,7,2,4,2,3,4,2] from collections import defaultdict res = defaultdict(list) nums.sort()
- first we create a result dumber with a defaultdict type, then we do a loop
for num in nums: count = [0] * ( nums[-1] +1 +abs(nums[0]) )
- this equation creates a list in range with the smallest number and the biggest number
for example:
input = [ -3, -1, 0, 1, 5] count = [0,0,0,0,0,0,0,0] len(count) = range(-3,5) = 8
- think of it as [ -3, -2, -1, …, 5 ]