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;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_52212261/article/details/129231674
今日推荐