Lv.2arrayhashsorting
Top K Frequent Numbers
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums and an integer k, return the k values that appear most often, ordered by frequency
descending, and by value ascending among equal frequencies.
Examples
| nums | k | result |
|---|---|---|
[1, 1, 1, 2, 2, 3] | 2 | [1, 2] |
[4, -1, 4, -1, 7] | 3 | [-1, 4, 7] |
[9] | 1 | [9] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[], k: int) → int[]
Constraints
-
nums.length,nums[i] -
knumber of distinct values innums
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| nums | k | Expected |
|---|---|---|
[1,1,1,2,2,3] | 2 | [1,2] |
[4,-1,4,-1,7] | 3 | [-1,4,7] |
[9] | 1 | [9] |
Hint
Hint
Count with a hash map, then sort the distinct values by (-count, value) and take the first k. Looking up each element in
a plain list of distinct values is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1588 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 9 | verdict only |
| performance | 60 | 4 | verdict only |