Nearest Points on a Plane

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……



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