当前位置:网站首页>TopK
TopK
2022-04-22 14:13:00 【Borrow some hair】
TopK problem , Whether it's asking for the front K Big / front K Small / The first K Big / The first K Wait a minute , There are the following ways :
-
O(N): It is the most efficient way to solve TopK problem
-
O(NlogK): Big root pile ( front K Small )/ Heap ( front K Big )
-
O(NlogK): Binary search tree
-
O(N): In the case of limited data range , You can count and sort directly O(N) Efficient solution
347. front K High frequency elements
Given a non empty array of integers , Before returning the frequency of occurrence k High element .
Example 1:
Input : nums = [1,1,1,2,2,3], k = 2
Output : [1,2]
Example 2:
Input : nums = [1], k = 1
Output : [1]
Tips :
You can assume that given k Always reasonable , And 1 ≤ k ≤ The number of different elements in the array .
The time complexity of your algorithm must be better than O(n log n) , n Is the size of the array .
The question data guarantee the unique answer , let me put it another way , Before array k The set of high-frequency elements is unique .
You can return the answers in any order .
Answer key :
1)Hashmap
use map Record the number of occurrences of the element , Find the number of occurrences of the most frequent element , Add to the result array according to the number of occurrences
2) Pile up
As above, record the number of occurrences , Form an array of occurrences , Find its front k Big . Build a small top heap to traverse . If the number of elements in the heap is less than k, You can insert it directly into the heap .
If the number of elements in the heap is equal to k, Then check the size of the heap top and the current occurrence times . If the top of the pile is larger , It means at least k The number of occurrences is greater than the current value , Therefore, the current value is discarded ; otherwise , Just pop out of the top of the pile , Insert the current value into the heap . After traversal , The elements in the heap represent 「 Number of occurrences array 」 Middle front k Big value
solution:
1)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
int res[]=new int[k];
Map<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);
}
int maxTimes=0;
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
if(entry.getValue() > maxTimes){
maxTimes = entry.getValue();
}
}
while(k > 0){
for(Map.Entry<Integer, Integer> entry : map.entrySet()){
if(entry.getValue() == maxTimes){
res[k - 1] = entry.getKey();
k--;
}
}
maxTimes--;
}
return res;
}
}
2)
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> occurrences = new HashMap<Integer, Integer>();
for (int num : nums) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}
// int[] The first element of represents the value of the array , The second element represents the number of times the value appears
PriorityQueue<int[]> queue = new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m, int[] n) {
return m[1] - n[1];
}
});
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int num = entry.getKey(), count = entry.getValue();
if (queue.size() == k) {
if (queue.peek()[1] < count) {
queue.poll();
queue.offer(new int[]{
num, count});
}
} else {
queue.offer(new int[]{
num, count});
}
}
int[] ret = new int[k];
for (int i = 0; i < k; ++i) {
ret[i] = queue.poll()[0];
}
return ret;
}
}
Map yes java The interface ,Map.Entry yes Map An internal interface for .
Map Provides some common methods , Such as keySet()、entrySet() Other methods .
keySet() Method return value is Map in key Collection of values ;entrySet() The return value of also returns a Set aggregate , The type of this collection is Map.Entry.
Map.Entry yes Map An internal interface for declarations , This interface is generic , Defined as Entry<K,V>. It said Map One of the entities in ( One key-value Yes ). There are getKey(),getValue Other methods
版权声明
本文为[Borrow some hair]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221411324097.html
边栏推荐
- Detailed explanation of channel implementation of cocoyaxi Library
- Mysql database transferring SQL file
- BinaryTree练习 从前序与中序、中序与后序遍历序列构造二叉树||重构二叉树654、105、106
- 【论文笔记】Vision Transformers for Dense Prediction
- HashTable哈希表练习查找插入删除217、349 、202、287、290、532、205、128
- CPT 104_ Lab 09
- Binary tree practice binary tree traversal recursion 257, 100, 222, 101, 226, 437, 563, 617, 572, 543, |687
- Solution to the blank page of small and medium-sized programs running from uniapp to wechat developer tool
- Move blog to CSDN
- Golang:包管理
猜你喜欢

985 official announcement: international ranking is no longer a construction goal!

When getting the value in the database, the database has a value, but it is empty??

Huawei cloud media Zha Yong: Huawei cloud's technical practice in the field of video AI transcoding

Actual combat of wechat applet mall project (Part 6: commodity search)

Independent station operation | 6 Facebook promotion tips, do you know?

Golang:包管理

POM in idea Mysql5. XML file 7 coordinate red error

P2B论文复现——点云学习记录

An error is reported when reading the attribute value of the object through the variable storage key value in TS (TS: 7053)

【论文笔记】Vision Transformers for Dense Prediction
随机推荐
BCC-funccount
链表 环形链表 链表判环 寻找入环节点141、142
TopK
[robot learning] learning record of mobile robot odometer
C语言的三子棋,用22天总结了一份完美的SQL学习笔记
Exercises and answers for the examination of main principals of hazardous chemical business units in 2022
PLSQL developer file encoding format setting
日志脱敏是什么意思?为什么要做日志脱敏?
Brief description of three elements of LAN characteristics
Is it effective to control caching through meta information in HTML files? Is it used much at present?
Solution to the blank page of small and medium-sized programs running from uniapp to wechat developer tool
Actual combat of wechat applet mall project (Part 6: commodity search)
HashTable哈希表与统计594、350、|554、609、454、18
Tools applicable to any database - Shanghai daoning brings a powerful general database management tool dbeaver to developers and database administrators
关于半导体的8个奇特事实
When getting the value in the database, the database has a value, but it is empty??
Ebpf learning - getting started
双指针||有序数组去重 排序链表移除元素 26、27、83
Shiro之缓存管理
How to use openfeign to call the third-party interface