- 前 K 个高频元素
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]
提示:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
你可以按任意顺序返回答案。
// #define debug
#ifdef debug
#include <time.h>
#include "win_majiao.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)1e5+7)
#define ll long long int
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO{
char print_f[105];
void read() {}
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int a[MAXN];
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> mp;
for(auto x : nums) mp[x] ++;
vector<pair<int,int> > vec;
vector<int> ans;
for(auto it : mp) {
int num = it.first, cnt = it.second;
vec.push_back({cnt, num});
}
sort(vec.begin(), vec.end());
for(int i=mp.size()-1; k; i--, k--) {
ans.push_back(vec[i].second);
}
return ans;
}
};
#ifdef debug
signed main() {
Solution s;
vector<int> vec = { 1,1,1,2,2,3 };
vec = s.topKFrequent(vec, 2);
forvec(vec);
return 0;
}
#endif
java代码
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
class Node implements Comparable<Node> {
int fst, sec;
@Override
public int compareTo(Node o) {
if(fst == o.fst) return sec < o.sec ? 1 : (sec==o.sec ? 0 : -1);
return fst < o.fst ? 1 : -1;
}
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
PriorityQueue<Node> q = new PriorityQueue<>();
Map<Integer, Integer> mp = new HashMap<>();
for(int i=0; i<nums.length; i++) {
if(mp.containsKey(nums[i]))
mp.put(nums[i], mp.get(nums[i])+1);
else
mp.put(nums[i], 1);
}
Set<Map.Entry<Integer, Integer>> en = mp.entrySet();
for(Map.Entry e : en) {
Node no = new Node();
no.sec = (int) e.getKey();
no.fst = (int) e.getValue();
q.add(no);
}
int ans[] = new int[k];
while(k-- > 0) {
Node poll = q.poll();
ans[k] = poll.sec;
}
return ans;
}
}
public class Main {
public static final boolean debug = true;
public static String INPATH = "C:\\Users\\majiao\\Desktop\\test.txt",
OUTPATH = "C:\\Users\\majiao\\Desktop\\out.txt";
public static StreamTokenizer tok;
public static BufferedReader cin;
public static PrintWriter cout;
public static long start_time = 0, out_time = 0;
public static int n, m, K, Q, MAXN = (int)1e5+7, INF = 0x3f3f3f3f;
public static byte buf[] = new byte[MAXN];
public static void main(String[] args) throws IOException {
main_init();
if(debug) { start_time = System.currentTimeMillis(); }
if(false) { System.setOut(new PrintStream(OUTPATH)); }
Solution s = new Solution();
int vec[] = { 1,1,1,2,2,3 };
int[] ints = s.topKFrequent(vec, 2);
for(int i=0; i<ints.length; i++)
System.out.println(ints[i]);
if(debug) {
out_time = System.currentTimeMillis();
cout.printf("run time : %d ms\n", out_time-start_time);
}
cout.flush();
}
public static void main_init() {
try {
if (debug) {
cin = new BufferedReader(new InputStreamReader(
new FileInputStream(INPATH)));
} else {
cin = new BufferedReader(new InputStreamReader(System.in));
}
cout = new PrintWriter(new OutputStreamWriter(System.out));
// cout = new PrintWriter(OUTPATH);
tok = new StreamTokenizer(cin);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String next_str() {
try {
tok.nextToken();
if (tok.ttype == StreamTokenizer.TT_EOF)
return null;
else if (tok.ttype == StreamTokenizer.TT_NUMBER) {
return String.valueOf((int)tok.nval);
} else if (tok.ttype == StreamTokenizer.TT_WORD) {
return tok.sval;
} else return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static int read_int() {
String tmp_next_str = next_str();
return null==tmp_next_str ? -1 : Integer.parseInt(tmp_next_str);
}
public static long read_long() { return Long.parseLong(next_str()); }
public static double read_double() { return Double.parseDouble(next_str()); }
public static BigInteger read_big() { return new BigInteger(next_str()); }
public static BigDecimal read_dec() { return new BigDecimal(next_str()); }
}