当前位置:网站首页>Leetcode skimming: stack and queue 06 (top k high-frequency elements)
Leetcode skimming: stack and queue 06 (top k high-frequency elements)
2022-07-02 00:26:00 【Taotao can't learn English】
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 ) O(n \log n) O(nlogn) , 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 .
It's another medium-sized problem, and one hit the soul , Gone with the wind hhhhh
Ideas :
The hash table calculates the number of occurrences of each number
key 、 Values are put into two arrays , Sort by value , Key image synchronous transformation position
Return to the former K A digital .
package com.programmercarl.stacks_queues;
import java.util.HashMap;
/** * @ClassName TopKFrequent * @Descriotion TODO * @Author nitaotao * @Date 2022/6/30 14:13 * @Version 1.0 * https://leetcode.cn/problems/top-k-frequent-elements/ * 347. front K High frequency elements **/
public class TopKFrequent {
public static int[] topKFrequent(int[] nums, int k) {
/** * Ideas : * Hash table count */
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);
}
}
int[] keys = new int[map.size()];
int[] values = new int[map.size()];
int index = 0;
for (Integer key : map.keySet()) {
keys[index] = key;
values[index] = map.get(key);
index++;
}
//value Sort ,key Image synchronization Exchange
for (int i = 0; i < values.length-1; i++) {
for (int j = i+1; j < values.length; j++) {
if (values[i] < values[j]) {
int tempValue = values[i];
values[i] = values[j];
values[j] = tempValue;
int tempKey = keys[i];
keys[i] = keys[j];
keys[j] = tempKey;
}
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = keys[i];
}
return result;
}
}
There is another way to look at the solution , It's the train of thought that our teacher said in class before , Big top pile idea .
public static int[] topKFrequent(int[] nums, int k) {
/** * Ideas : * Hash table count */
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);
}
}
// Big top pile idea
// Priority queue , Sort by value size
PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
for(Map.Entry<Integer,Integer>entry : map.entrySet()) {
queue.offer(entry);
// Before retention only k Number
if (queue.size() > k) {
queue.poll();
}
}
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = queue.poll().getKey();
}
return result;
}
边栏推荐
- 4. Object mapping Mapstercover
- 【QT】测试Qt是否能连接上数据库
- 【模板】自适应辛普森积分
- [QT] qtcreator uninstall and installation (abnormal state)
- Which securities company is safer to open a stock account
- 数据库--SqlServer详解
- Selectively inhibiting learning bias for active sampling
- Windows installation WSL (II)
- UVM tutorial
- Jielizhi, production line assembly link [chapter]
猜你喜欢
B tree and b+tree of MySQL
Ldr6035 smart Bluetooth audio can continuously charge and discharge mobile devices
[cmake] cmake configuration in QT Creator
Data analysis methodology and previous experience summary [notes dry goods]
Kyushu cloud and Intel jointly released the smart campus private cloud framework, enabling new infrastructure for education
使用多线程Callable查询oracle数据库
PWN attack and defense world cgpwn2
SQL数据分析之窗口排序函数rank、dense_rank、raw_number与lag、lead窗口偏移函数【用法整理】
Dongge cashes in and the boss retires?
【QT】测试Qt是否能连接上数据库
随机推荐
I would like to ask, which securities is better for securities account opening? Is it safe to open a mobile account?
Learn online case practice
Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]
Relevant settings of wechat applet cache expiration time (recommended)
Linux centos7 installation Oracle11g super perfect novice tutorial
Download the online video m3u8 tutorial
Ldr6035 smart Bluetooth audio can continuously charge and discharge mobile devices
一个实习生的CnosDB之旅
启牛学院开户安全的吗?开户怎么开?
Vue force cleaning browser cache
Jielizhi, production line assembly link [chapter]
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
Is the securities account given by qiniu business school safe? Where can I open an account
Barbie q! How to analyze the new game app?
Graduation season is both a farewell and a new beginning
Jielizhi, production line assembly link [chapter]
Accelerator systems initiative is an independent non-profit organization
leetcode96不同的二叉搜索树
2022拼多多详情/拼多多商品详情/拼多多sku详情
在证券账户上买基金安全吗?哪里可以买基金