算法课程-共线点-作业

该博客探讨了如何在一个平面上找出共线的点,并介绍了实现这一功能的point类和查找共线点的算法。算法复杂度分别达到了N^4和N^2*lgN。博主首先解释了题意,然后详细分析了问题,强调了在按斜率排序的点集中找到共线点首尾的难点。最后,提供了算法思路和代码注释。
摘要由CSDN通过智能技术生成

题意理解

实现在一个平面的点中找出共线的点,并标记共线点的头尾(即线段)。要求实现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
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值