题意理解
实现在一个平面的点中找出共线的点,并标记共线点的头尾(即线段)。要求实现point类和查找共线点的类。算法复杂度分别是N^4 和N^2*lgN.
问题分析
详见代码注释
最难的部分是如何根据按斜率排序后的点集,找到共现点点首尾,且只输出一次。算法的思路是先按照各点的斜率排序,然后按照指定点的斜率排序,相同斜率的点就是满足共线的点,同时通过compareto方法,保证共线的点只输出一次。
其他
https://www.cnblogs.com/cnu4/articles/3998106.html
链接
/******************************************************************************
* Compilation: javac Point.java
* Execution: java Point
* Dependencies: none
*
* An immutable data type for points in the plane.
* For use on Coursera, Algorithms Part I programming assignment.
*
******************************************************************************/
import edu.princeton.cs.algs4.StdDraw;
import java.util.Comparator;
public class Point implements Comparable<Point> {
// public static final Comparator<Point> By_Slope = new BySlope();
private final int x; // x-coordinate of this point
private final int y; // y-coordinate of this point
/**
* Initializes a new point.
*
* @param x the <em>x</em>-coordinate of the point
* @param y the <em>y</em>-coordinate of the point
*/
public Point(int x, int y) {
/* DO NOT MODIFY */
this.x = x;
this.y = y;
}
/**
* Draws this point to standard draw.
*/
public void draw() {
/* DO NOT MODIFY */
StdDraw.point(x, y);
}
/**
* Draws the line segment between this point and the specified point
* to standard draw.
*
* @param that the other point
*/
public void drawTo(Point that) {
/* DO NOT MODIFY */
StdDraw.line(this.x, this.y, that.x, that.y);
}
/**
* Returns the slope between this point and the specified point.
* Formally, if the two points are (x0, y0) and (x1, y1), then the slope
* is (y1 - y0) / (x1 - x0). For completeness, the slope is defined to be
* +0.0 if the line segment connecting the two points is horizontal;
* Double.POSITIVE_INFINITY if the line segment is vertical;
* and Double.NEGATIVE_INFINITY if (x0, y0) and (x1, y1) are equal.
*
* @param that the other point
* @return the slope between this point and the specified point
*/
public double slopeTo(Point that) {
/* YOUR CODE HERE */
if (this.x == that.x &&am