1. 程式人生 > >Top K Frequent Elements 選出陣列中出現次數最多的k個元素

Top K Frequent Elements 選出陣列中出現次數最多的k個元素

原題地址:https://leetcode.com/problems/top-k-frequent-elements/,這個題目要求時間複雜度不能超過O(nlgn),也就是說常規的排序演算法不可行(排序演算法複雜度至少為nlgn)。那麼想到的一種演算法是使用優先佇列,限制優先佇列的大小為K,那麼可以做到時間複雜度為O(nlgk),還能不能再提高呢,另一種方法是使用桶排序,演算法複雜度為O(n)。

方法1:使用優先佇列,首先要做的統計每個數字出現的次數,這個統計放在一個HashMap中,然後用PriorityQueue來找出結果,因為在PriorityQueue中要藉助HashMap來實現排序(將key按照value升序排序),所以在PriorityQueue的建構函式中要把Map當引數傳遞進去。

程式碼為:

	//返回一個數組中,出現次數最多的k個數  
    public List<Integer> topKFrequent2(int[] nums, int k) {
    
    	//先統計每個數字出現的次數,這個貌似不可避免,時間複雜度為O(n)
    	HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    	for(int i=0;i<nums.length;i++){
    		Integer count = map.get(nums[i]);
    		if(count==null){
    			count = 0;
    		}
    		map.put(nums[i], count+1);
    	}
    	
    	//然後應該可以使用優先隊列了,
    	PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k,new Comp(map));
    	
    	for(int key:map.keySet()){
    		if(pq.size()<k){
    			pq.add(key);
    			continue;
    		}
    		
    		int small = pq.peek();
    		if(map.get(small)<map.get(key)){
    			pq.poll();
    			pq.add(key);
    		}
    	}
    	return new ArrayList<Integer>(pq);
    }
    
    //注意建構函式,使用map來初始化
    class Comp implements Comparator<Integer>{

    	HashMap<Integer,Integer> map;
    	public Comp(HashMap<Integer,Integer> map){
    		this.map = map;
    	}
    	 
		@Override  //通過key的value來排序
		public int compare(Integer o1, Integer o2) {
			return map.get(o1)-map.get(o2);
		}
    	
    }

方法二:

桶排序的時間複雜度為O(n),空間複雜度也是O(n),這個桶排序實際上是將統計數字出現次數的Map逆轉一下

程式碼:

     * 求一個數組中,出現次數最多的k個數,利用桶排序的思想,注意這裡的桶排序空間
     * 複雜度為O(n),桶的下標表示出現的次數,桶的元素是一個List,表示所有出現了
     * 這些次數的元素,厲害
     * */
    public List<Integer> topKFrequent(int[] nums, int k) {
    	
    	//第一步,還是先統計每個數字出現的次數,這個貌似不可避免,時間複雜度為O(n)
    	HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
    	for(int i=0;i<nums.length;i++){
    		Integer count = map.get(nums[i]);
    		if(count==null){
    			count = 0;
    		}
    		map.put(nums[i], count+1);
    	}
    	
    	//第二步,構造一個桶,下標表示出現次數,如果nums大小為n,且這n個數相等,那麼
    	//出現次數最大為n,所有桶的大小為n+1
    	//這個桶實際上是將上面那個map的key value翻轉了一下,因為對於同一個value可能有多個
    	//key,所以buckey的元素應該是個列表,第一次這麼用列表
    	List<Integer>[] bucket = new List[nums.length+1];
    	
    	for(int key:map.keySet()){
    		int count = map.get(key);
    		if(bucket[count]==null){
    			ArrayList<Integer> temp = new ArrayList<Integer>();
    			temp.add(key);
    			bucket[count] = temp;
    		}else{
    			bucket[count].add(key);
    		}
    	}
    	
    	ArrayList<Integer> res = new ArrayList<Integer>();
    	for(int i=bucket.length-1;i>=0&&res.size()<k;i--){
    		if(bucket[i]!=null){
    			//這裡addAll是因為題目說明了只有一個唯一解,是個特例
    			res.addAll(bucket[i]);
    		}
    	}
    	return res;
    }