[CareerCup] 7.6 The Line Passes the Most Number of Points 经过最多点的直线

7.6 Given a two-dimensional graph with points on it, find a line which passes the most number of points.

这道题给了我们许多点,让我们求经过最多点的一条直线。给之前那道7.5 A Line Cut Two Squares in Half 平均分割两个正方形的直线一样,都需要自己写出点类和直线类。在直线类中,我用我们用斜率和截距来表示直线,为了应对斜率不存在情况,我们还需用一个flag来标记是否为垂直的线。在直线类中,我们要有判断两条直线是否相等的函数。判断相等的方法和之前那道7.3 Line Intersection 直线相交相同,都需要使用epsilon,只要两个数的差值的绝对值小于epsilon,我们就认定是相等的。对于给定的所有点,每两个点能组成一条直线,我们的方法是遍历所有的直线,把所有相同的直线都存入哈希表中,key是直线的斜率,映射关系是斜率和直线集合的映射,那么我们只需找到包含直线最多的那个集合即可,参见代码如下:

class Point {
public:
    double _x, _y;
    Point(double x, double y): _x(x), _y(y) {};
};

class Line {
public:
    static constexpr double _epsilon = 0.0001;
    double _slope, _intercept;
    bool _infi_slope = false;
    Line(Point p, Point q) {
        if (fabs(p._x - q._x) > _epsilon) {
            _slope = (p._y - q._y) / (p._x - q._x);
            _intercept = p._y - _slope * p._x;
        } else {
            _infi_slope = true;
            _intercept = p._x;
        }
    }
    static double floorToNearestEpsilon(double d) {
        int r = (int)(d / _epsilon);
        return ((double)r) * _epsilon;
    }
    bool isEquivalent(double a, double b) {
        return (fabs(a - b) < _epsilon);
    }
    bool isEquivalent(Line other) {
        if (isEquivalent(_slope, other._slope) && isEquivalent(_intercept, other._intercept) && (_infi_slope == other._infi_slope)) {
            return true;
        }
        return false;
    }
};

class Solution {
public:
    Line findBestLine(vector<Point> &points) {
        Line res(points[0], points[1]);
        int bestCnt = 0;
        unordered_map<double, vector<Line> > m;
        for (int i = 0; i < (int)points.size(); ++i) {
            for (int j = i + 1; j < (int)points.size(); ++j) {
                Line line(points[i], points[j]);
                insertLine(m, line);
                int cnt = countEquivalentLines(m, line);
                if (cnt > bestCnt) {
                    res = line;
                    bestCnt = cnt;
                }
            }
        }
        return res;
    }
    void insertLine(unordered_map<double, vector<Line> > &m, Line &line) {
        vector<Line> lines;
        double key = Line::floorToNearestEpsilon(line._slope);
        if (m.find(key) != m.end()) {
            lines = m[key];
        } else {
            m[key] = lines;
        }
        lines.push_back(line);
    }
    int countEquivalentLines(unordered_map<double, vector<Line> > &m, Line &line) {
        double key = Line::floorToNearestEpsilon(line._slope);
        double eps = Line::_epsilon;
        return countEquivalentLines(m[key], line) + countEquivalentLines(m[key - eps], line) + countEquivalentLines(m[key + eps], line);
    }
    int countEquivalentLines(vector<Line> &lines, Line &line) {
        if (lines.empty()) return 0;
        int res = 0;
        for (auto &a : lines) {
            if (a.isEquivalent(line)) ++res;
        }
        return res;
    }
};
时间: 2024-12-29 23:40:29

[CareerCup] 7.6 The Line Passes the Most Number of Points 经过最多点的直线的相关文章

[CC150] Find a line passing the most number of points

Problem: Given a two-dimensional graph with points on it, find a line which passes the most number of points. 此题是Cracking the code 5th edition 第七章第六题,思路就是 n choose 2, 所以时间复杂度是O(n^2),因为没有更快的办法. 此题的难点在于两点一线计算出的斜率是浮点型,不好比较equality.所以其中需要有一个精确到哪一位的概念,英文是

[LeetCode OJ] Max Points on a Line—Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

//定义二维平面上的点struct Point { int x; int y; Point(int a=0, int b=0):x(a),y(b){} }; bool operator==(const Point& left, const Point& right) { return (left.x==right.x && left.y==right.y); } //求两个点连接成的直线所对应的斜率 double line_equation(const Point&

[CareerCup] 7.5 A Line Cut Two Squares in Half 平均分割两个正方形的直线

7.5 Given two squares on a two-dimensional plane, find a line that would cut these two squares in half. Assume that the top and the bottom sides of the square run parallel to the x-axis 这道题给了我们两个正方形,让我们求一条可以讲这两个正方形平均分为两个部分的直线,前提是两个正方形都和x轴平行.那么我们首先要知道

CareerCup All in One 题目汇总

Chapter 1. Arrays and Strings 1.1 Unique Characters of a String 1.2 Reverse String 1.3 Permutation String 1.4 Replace Spaces 1.5 Compress String 1.6 Rotate Image 1.7 Set Matrix Zeroes 1.8 String Rotation Chapter 2. Linked Lists 2.1 Remove Duplicates

Careercup | Chapter 7

7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only the add operator. 比较简单.但是要封装得好. 7.5 Given two squares on a two-dimensional plane, find a line that would cut these two squares in half. Assume that th

OpenCV Tutorials &mdash;&mdash; Hough Line Transform

霍夫直线变换 -- 用于检测图像中的直线 利用图像空间和Hough参数空间的点--直线对偶性,把图像空间中的检测问题转换到参数空间,通过在参数空间进行简单的累加统计,然后在Hough参数空间中寻找累加器峰值的方法检测直线 Standard and Probabilistic Hough Line Transform OpenCV implements two kind of Hough Line Transforms: The Standard Hough Transform It consis

iOS Drawing Concepts[iOS 绘画概念]

iOS Drawing Concepts https://developer.apple.com/library/ios/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GraphicsDrawingOverview/GraphicsDrawingOverview.html High-quality graphics are an important part of your app’s user interface. Providin

POJ 题目1106 Transmitters(数学几何)

Transmitters Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 4756   Accepted: 2538 Description In a wireless network with multiple transmitters sending on the same frequencies, it is often a requirement that signals don't overlap, or at

iOS 绘制1像素的线

一.Point Vs Pixel iOS中当我们使用Quartz,UIKit,CoreAnimation等框架时,所有的坐标系统采用Point来衡量.系统在实际渲染到设置时会帮助我们处理Point到Pixel的转换. 这样做的好处隔离变化,即我们在布局的事后不需要关注当前设备是否为Retina,直接按照一套坐标系统来布局即可. 实际使用中我们需要牢记下面这一点: One point does not necessarily correspond to one physical pixel. 1