Problem Statement
Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
Approach
Count frequencies with hash map, then use bucket sort or heap to find top k elements.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | O(n) with bucket sort |
| Space | O(n) |
Examples
Example 1
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Explanation: 1 appears 3 times, 2 appears 2 times
Example 2
Input: nums = [1], k = 1
Output: [1]
Constraints
- βΈ
1 <= nums.length <= 10^5 - βΈ
-10^4 <= nums[i] <= 10^4 - βΈ
kis in the range[1, number of unique elements]
Loading...
Sign in to run your code...
Asked by companies:
AmazonFacebookAppleGoogle