K Closest Points
来源:互联网 发布:在a标签传参数js 编辑:程序博客网 时间:2024/05/23 12:53
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>(){@Overridepublic int compare(CPoint c1, CPoint c2) {// TODO Auto-generated method stubdouble 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 rulesPriorityQueue<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
- K Closest Points
- K Closest Points
- K closest points to a given point
- Sicily 1961. Closest Points
- The Closest M Points
- Kth closest points
- HDU4347 The Closest M Points
- Closest Pair of Points - C++
- [BZOJ3053]The Closest M Points
- hdu4347-The Closest M Points
- HDU4347-The Closest M Points
- Find K Closest Elements
- Geeks面试题: Closest Pair of Points
- poj:4091:The Closest M Points
- 【BZOJ 3053】 The Closest M Points
- HDU 4347 The Closest M Points
- closest pair of points(O(nlogn)) solution
- 【35.43%】【hdu 4347】The Closest M Points
- 用Eratosthenes筛子算法,求解从2到n之间的素数
- 线性表详解(c语言版)
- java正则表达式的匹配结果遍历方法find()和matches()不同
- 传输层安全协议(TLS)1.2版
- EPM问题汇总之规则运行时间过长总是提示
- K Closest Points
- [BZOJ1251]序列终结者
- Android Jni开发之eclipse中自动化编译javah
- EPM问题汇总之----Planning打印乱码
- Ninja介绍
- iOS微信第三方登录实现
- EPM修改admin用户
- Oc-语句总结(2)--NSArray
- 士兵突击的影响