TopKElements和Hashmap的空间复杂度问题
来源:互联网 发布:windows xp系统重装 编辑:程序博客网 时间:2024/05/22 11:02
hashmap的空间复杂度,比如,we need to find the top frequency word in an array,so we need to use hashmap then the space complexity is O(n).
if we use brute force method,firstly,sort the array,it cost O(nlgn) time,then the space complexity is O(1), just need to create a variable count,to count the elements
Method1: brute force:对数组进行排序,之后再从后面往前面遍历整个数组找出k个最大的元素,考虑到数组中是否有duplicate的元素的时候,如果有duplicate元素,就可以用TreeSet的来解决,遍历一遍数组 将数组全部放进TreeSet里面 再取出来K最大的元素
Method2:在Java里面创建PriorityQueue, 使用小顶堆,创建k个元素的小顶堆
public class TopKelement { PriorityQueue<Integer> minheap; // PriorityQueue<Integer> minheap; private int maxSize; public TopKelement(int maxSize){ if(maxSize<=0) throw new IllegalArgumentException(); this.maxSize = maxSize; this.minheap = new PriorityQueue<Integer>(maxSize, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }); } public void add(int num){ if(minheap.size()<maxSize){ minheap.add(num); }else{ int peek = minheap.peek(); if(num>peek){ minheap.poll(); minheap.add(num); } } } public void print(){ for(int i=0;i<maxSize;i++){ System.out.println(minheap.poll()); } }}
0 0
- TopKElements和Hashmap的空间复杂度问题
- 算法的时间和空间复杂度问题
- 【c++】关于时间复杂度和空间复杂度的相关问题
- 时间的复杂度和空间的复杂度
- 时间复杂度和空间复杂度的概念
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 【SSH进阶之路】Spring的IOC逐层深入——依赖注入的两种实现类型(四)
- OCX和DLL的区别--OCX控件的应用
- 【POJ3207】Ikki's Story IV - Panda's Trick【2-SAT】
- 亲测实验,stm32待机模式和停机模式唤醒程序的区别,以及唤醒后程序入口。
- 程序员面试金典(动态规划):8(n)皇后问题(java解法)
- TopKElements和Hashmap的空间复杂度问题
- 判断字符串是否没有重复字符
- 编译个性化的openwrt固件
- [Java]根据文件取得Mime Type的各种方法
- 观察者模式
- sql Server 锁
- HTML5 canvas绘制雪花飘落动画(需求分析、知识点、程序编写分布详解)
- php中模拟POST提交数据两种方法
- [Android] 获取文件的MIME类型