Cho mảng số nguyên và số K. Tìm K phần tử có tần suất xuất hiện cao nhất. Ví dụ:
Đầu vào 1: N=6, K=2, arr={1,1,1,2,2,3} → Đầu ra: 1 2.
Đầu vào 2: N=2, K=1, arr={1,2} → Đầu ra: 1 (hoặc 2, tần suất bằng nhau).
Phương pháp: Hashmap + Sắp xếp theo tần suất
- Đếm tần suất mỗi phần tử bằng
unordered_map. - Chuyển map sang vector cặp
<giá trị, tần suất>. - Sắp xếp vector giảm dần theo tần suất.
- In K phần tử đầu tiên.
Ví dụ mã nguồn
#include <bits/stdc++.h>
using namespace std;
bool cmp(pair<int,int> a, pair<int,int> b) {
return a.second > b.second;
}
void topKFrequent(int arr[], int n, int k) {
unordered_map<int,int> mp;
for (int i=0;i
Kết quả
1 2
Lưu ý: mã gốc có lỗi biến nums chưa khai báo; đã sửa dùng arr.