leetcode 困难 —— 直线上最多的点数(简单逻辑题)

(非常简单的一道逻辑题)

题目:
给你一个数组 points ,其中 points[i] = [xi, yi] 表示 X-Y 平面上的一个点。求最多有多少个点在同一条直线上。

题解:
只用考虑从每个点出发,最多有多少个点在同一条直线上

那直接遍历其他每个点,计算其他每个点与当前点的斜率即可
看斜率相同的数量最高的值

怎么保存斜率呢,小数精度存在点问题,那就保存分数(分子和分母需要约分)
然后用一个 map 存储斜率相同的数量即可,即 map<pair<int, int>, int>

代码如下:

class Solution {
public:
    int gcd(int a, int b) {
        return a % b == 0 ? b : gcd(b, a % b);
    }
    vector<pair<int, int> > points_temp;
    int maxPoints(vector<vector<int>>& points) {
        for(int i = 0; i < points.size(); i++) {
            points_temp.push_back(make_pair(points[i][0], points[i][1]));
        }
        sort(points_temp.begin(), points_temp.end());
        int res = 1;
        map<pair<int, int>, int> temp;
        for(int i = 0; i < points_temp.size(); i++) {
            temp.clear();
            for(int j = i + 1; j < points_temp.size(); j++) {
                int x = points_temp[j].first - points_temp[i].first;
                int y = points_temp[j].second - points_temp[i].second;
                if(x == 0) {
                    y = 1;
                }
                else if(y == 0) {
                    x = 1;
                }
                else {
                    int t = gcd(x, y);
                    x = x / t;
                    y = y / t;
                }
                pair<int, int> p = make_pair(x, y);
                if(temp.count(p) == 0) {
                    temp[p] = 2;
                }
                else {
                    temp[p] = temp[p] + 1;
                }
                res = max(res, temp[p]);
            }
       }
       return res;
    }
};
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值