347. Top K Frequent Elements-获得前K高次元素

347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].

Note: 

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

题意:返回数组中出现次数前K高的元素:

public class Solution {
    public List topKFrequent(int[] array, int k) {
      HashMap  hm = new HashMap();
		List Ls = new ArrayList();
		int value=0;
		for(int i = 0; i < array.length; i++){
			if(hm.containsKey(array[i])){
				hm.put(array[i],hm.get(array[i])+1 );
			}else{
				hm.put(array[i], 1);
			}
		}
		List> entryList = new ArrayList>(hm.entrySet());
		for (int i = 0; i < entryList.size(); i++) {
		    System.out.println(entryList.get(i));
		}
		Collections.sort(entryList, new Comparator>() {   
		    public int compare(Map.Entry o1, Map.Entry o2) {      
		    	return (o2.getValue() - o1.getValue());//根据value排序
		        //return (o1.getKey()).toString().compareTo(o2.getKey());
		    }
		});
		for (int i = 0; i < k; i++) {
			Ls.add(entryList.get(i).getKey());
		}
		return Ls;
    }
}
第一独立完成那么长的代码,虽然过程有点麻烦,也上网查了资料,但是这个是我自己写出来的啊。

效率不太高,OJ测试时耗时102ms,想想 就是一个长时间。

原文链接:https://leetcode.com/problems/top-k-frequent-elements/


你可能感兴趣的:(347. Top K Frequent Elements-获得前K高次元素)