首页 > 其他 > 详细

使用PriorityQueue实现topK

时间:2020-12-30 13:37:12      阅读:38      评论:0      收藏:0      [点我收藏+]
package com.github.ralgond.yousuggest;

import java.util.Comparator;
import java.util.PriorityQueue;

public class Test0 {

	public static void main(String args[]) {
		int topK = 5;
		
		Comparator<Integer> cmp = new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				if (o2 > o1)
					return -1;
				else if (o2 < o1)
					return 1;
				return 0;
			}
		};
		
		PriorityQueue<Integer> pq = new PriorityQueue<>(topK, cmp);
		
		
		for (int i = 0; i < 10; i++) {
			if (pq.size() < topK)
				pq.add(i);
			else {
				if (pq.comparator().compare(i, pq.peek()) > 0) {
					pq.poll();
					pq.add(i);
				}
			}
		}
		
		for (int i : pq) {
			System.out.println(i);
		}
	}
}

使用PriorityQueue实现topK

原文:https://www.cnblogs.com/ralgo/p/14210740.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!