常见算法 - 求给定数组中出现频率最高的前n个数

(leetcode347):

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].

思路:(常规)遍历数组,记录数值及对应的频率,再排序找出前k个。

            用map存储数值及对应频率,用优先队列找出前k个,优先队列可以直接存储map、排序,方便。Java这里的优先队列默认是最小堆实现, 比如对int就是优先级:从小到大。所以自定义比较器时要注意。

public class L347TopKFrequentElements {

	public static List topKFrequent(int[] nums, int k) {
		
		List list = new ArrayList(); 
		HashMap 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);
			}
		}
//		System.out.println(map);
		PriorityQueue pb = new PriorityQueue();
		for(Map.Entry entry : map.entrySet()){
			pb.add(new Element(entry.getKey(), entry.getValue()));
		}
		for (int i = 0; i < k; i++) {
			list.add(pb.poll().getNum());
		}
		return list;
		
	}
}

class Element implements Comparable{

	private Integer num;
	private Integer count;
	public Element(int num, int count) {
		super();
		this.num = num;
		this.count = count;
	}

	public Integer getNum() {
		return num;
	}


	public void setNum(Integer num) {
		this.num = num;
	}


	public Integer getCount() {
		return count;
	}


	public void setCount(Integer count) {
		this.count = count;
	}


	@Override
	public int compareTo(Element o) {
		return o.count.compareTo(this.count);
	}
	
}

你可能感兴趣的:(笔记,算法)