Max Points on a line ,在二维平面寻找共线的最多点

这篇博客探讨了在2D平面上找到最多共线点的问题。当n <= 2时,答案就是n。若n > 2,可以通过计算三点斜率来判断是否共线。博主提供了一个C++程序来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题描述如下:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

给定2维平面的N个点,找出共线的最多的点。

分析如下,初中知识,任何不相同的两点确定一条直线。

特殊情况,如果n <=2,共线的点n。

如果n>2怎么办呢? 给定三个点<x1, y1>, <x2, y2>, <x3, y3>,如果共线,我们会发现slop=(y2 -y1)/(x2-x1) = (y3 - y1)/(x3 - x1)。 请注意特殊情况如果三个点x值相同。

一下是c++程序.

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point> &points) {
        //special case
        if(points.size() <= 2) return points.size();
        
        int i, j, repeat, spc, max = 0;
        map<double, int> stat;
        for(i = 0; i < points.size(); i++){
            //fix each point, find the point
            repeat = 0; 
            spc = 0;
            stat.clear();
            Point point = points[i];
            
            for(j = 0; j < points.size(); j++){
                //if(i == j) continue;
                Point p2 = points[j];
                if(point.x == p2.x){
                    if(point.y == p2.y) repeat++; //also add self
                    else spc++;
                }else{
                    stat[(double)(p2.y-point.y)/(p2.x - point.x)] ++;
                }
            }
            for(map<double,int>::iterator begin = stat.begin(); begin != stat.end(); begin++){
                if(begin->second > spc) spc = begin->second;
            }
            if(max < (spc + repeat))max = spc + repeat;
        }
        return max;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值