K Closest Points

Given (0,0) as the centre and an array containing pair of coordinate such that 

(1,1)

(-2,4)

(3,4)

(-11,5)

...

(x,y).

If ask you return k closest points, how would you do it?

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

public class kclosestPoints {
	public static void main(String[] args){
		kclosestPoints kp = new kclosestPoints();
		CPoint c1 = new CPoint(1,1);
		CPoint c2 = new CPoint(-7,10);
		CPoint c3 = new CPoint(5,3);
		CPoint c4 = new CPoint(4,3);
		CPoint c5 = new CPoint(11,2);
		CPoint c6 = new CPoint(-14,-20);
		CPoint[] input = {c1,c2,c3,c4,c5,c6};
		for(CPoint k : kp.findClose(input, 3)){
			System.out.println(k.x+", "+k.y);
		}
	}
	
	public CPoint[] findClose(CPoint[] arr, int k){
		if(k==0)
			return new CPoint[0];
		Comparator<CPoint> cmp = new Comparator<CPoint>(){
			@Override
			public int compare(CPoint c1, CPoint c2) {
				// TODO Auto-generated method stub
				double d1 = c1.x * c1.x + c1.y*c1.y;
				double d2 = c2.x * c2.x + c2.y*c2.y;
				return  (int) (d1-d2);
			}
		};

		//k is capacity, cmp is an obj implementing Comparator, in which define the compare rules
		PriorityQueue<CPoint> heap = new PriorityQueue<CPoint>(k,  cmp);
		for(CPoint p : arr){
			heap.offer(p);  //offer is to input 
		}	
		
		CPoint[] res = new CPoint[k];
		for(int i=0;i<k;i++){
			res[i] = heap.poll(); //poll first k prior elements
		}
		return res;
		
	}
	
	static class CPoint{
		double x;
		double y;
		public CPoint(double a, double b){
			this.x = a;
			this.y = b;
		}
	}
}

这道题目是非常好的联系priorityqueue的机会,一般来说编程的顺序就是

先new一个cmp对象from Comparator接口,匿名类直接overwrite 里面的compare方法,里面复写自己compare方法。

然后new priorityqueue同时后面直接根据constructor new这个heap,两个参数,k代表capacity,cmp就是刚才new的comparator。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值