0%

Leetcode347 Top K Frequent Elements

Leetcode347 Top K Frequent Elements

题目描述

Given a non-empty array of integers, return the k\ most frequent elements.

Example 1:

1
2
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

1
2
Input: nums = [1], k = 1
Output: [1]

思路

首先使用hashmap统计词频,用priorityqueue按照词频排序,priorityqueue采用参数为数组。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int[] topKFrequent(int[] nums, int k) {
if(nums.length==0||nums.length==1) return nums;
int[] result = new int[k];
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(nums[i]))
map.put(nums[i],map.get(nums[i])+1);
else
map.put(nums[i],1);
}
Queue<int[]> q = new PriorityQueue<int[]>((a,b)->a[0]-b[0]);
for(Integer num : map.keySet()){
q.add(new int[]{map.get(num),num});
if(q.size()>k) q.poll();
}
for(int n=0;n<k;n++){
int[] tmp = q.poll();
result[n] = tmp[1];
}

return result;
}
}
-------------本文结束感谢您的阅读-------------

Welcome to my other publishing channels