码迷,mamicode.com
首页 > 其他好文 > 详细

Points on a Plane

时间:2016-01-24 06:59:23      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

Fill in the following methods:

 

public interface PointsOnAPlane {

    /**
     * Stores a given point in an internal data structure
     */
    void addPoint(Point point);

    /**
     * For given ‘center‘ point returns a subset of ‘m‘ stored points that are
     * closer to the center than others.
     *
     * E.g. Stored: (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
     *
     * findNearest(new Point(0, 0), 3) -> (0, 1), (0, 2), (0, 3)
     */
    Collection<Point> findNearest(Point center, int m);

}


解法一:用heap和hashmap,space用的好多啊……

HashMap<Points, Double> map;
private Comparator<Points> PointsComparator = new Comparator<Points>(){
    public int compare(Points A, Points B)
    {
        double distA = map.get(A);
        double distB = map.get(B);
        if(distA>distB) return 1;
        else if(distA<distB) return -1;
        else return 0;
    }
};

@Override 
public ArrayList<Points> findNearest(Points center, int m) { 
// TODO Auto-generated method stub
    map = new HashMap<Points,Double>();
    PriorityQueue<Points> q = new PriorityQueue<Points>(m,PointsComparator); 
    for (Points p : points){ 
        double dist =  Math.pow((center.getX() - p.getX()),2) + Math.pow((center.getY() - p.getY()),2) ; 
map.put(p,dist);
        q.add(p); 
    } 
    ArrayList<Points> nearestPoints = new ArrayList<Points>(); 
    for (int i = 0; i < m; i++){ 
        nearestPoints.add(q.poll()); 
    } 
    return nearestPoints; 
    } 
            

完整版本见eclipse……



Points on a Plane

标签:

原文地址:http://www.cnblogs.com/hygeia/p/5154490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!