leetcode Max Points on a Line

本文介绍了一种解决二维平面上求共线最大点数问题的算法。通过枚举点集中的每个点,并使用自定义分数类来表示斜率,利用map存储不同斜率对应的点数,最终找到共线的最大点数。

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

题目大意:二维平面上有n个点,求共线的最大点数

下面的算法定义了一个分数类来保存斜率,其中 分子分母同时为0的时候表示无穷的情况,分子为0,分母为1 表示斜率为0的情况

基本算法为 枚举+map操作

#include <vector>
#include <iostream>
#include <map>
using namespace std;
//自定义的分数  a表示分数  b表示分母
class Key
{
public:
    int a, b;
    Key(): a(0), b(0){}
    Key(int x, int y) : a(x), b(y){}
    friend bool operator < (const Key &k1, const Key &k2)
    {
        if(k1.a == k2.a)
            return k1.b < k2.b;
        return k1.a < k2.a;
    }
};
  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) {
        int n = points.size();
        map<Key, int> kmap;
        int d = 1; 
        int num = 0;
        for(int i = 0 ; i < n ; i++)
        {
            kmap.clear();
            Key k;
            kmap[k] = 0;
            d = 1; 
            for(int j = 0 ; j < n; j++)
            {
                if(i == j) continue;
                if(points[i].x == points[j].x )
                {
                    if(points[i].y == points[j].y)
                        d++;
                    else
                    {
                        k.a = 0;
                        k.b = 0;
                        kmap[k]++;
                    }
                }
                else
                {
                    int b = points[i].x - points[j].x;
                    int a = points[i].y - points[j].y;
                    int gab = gcd(a, b);
                    k.a = a / gab;
                    k.b = b / gab;
                    kmap[k]++;
                }
            }
            for(map<Key, int>::iterator it = kmap.begin(); it != kmap.end(); it++)
                if(num < it->second + d)
                    num = it->second + d;
        }
        return num;
    }
    int gcd(int a, int b)
    {
        if(b == 0)
            return a;
        return gcd(b, a % b);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值