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