xinyu04

导航

LeetCode 149 Max Points on a Line 思维

Given an array of points where points[i] = [xi, yi] represents a point on the \(X-Y\) plane, return the maximum number of points that lie on the same straight line.

Solution

我们需要求出最多多少个点在同一条直线上。考虑朴素做法:枚举第一个点和第二个点,求出斜率 \(O(N^2)\),再枚举第三个点统计多少个点有相同的斜率: \(O(N^3)\)

复杂度太高。我们可以枚举第一个点,和第二个点,再统计斜率出现的次数 (\(map\)). 因为如果这个斜率出现了 \(3\) 次,说明有三个点(不包括起始点)在这条线上。

\(\Large\textbf{Note: }\) 注意先处理相同位置的点以及垂直的情况(此时斜率我们用 \(INT\_MAX\)

点击查看代码
class Solution {
private:
    map<long double, int> slope;
    int ans = 0;
public:
    int maxPoints(vector<vector<int>>& points) {
        int n = points.size();
        for(int i=0;i<n;i++){
            slope.clear();
            int same_points = 1;
            for(int j=i+1;j<n;j++){
                if(points[i][0]==points[j][0] && points[i][1]==points[j][1]) same_points+=1;
                else if(points[i][0]==points[j][0]){
                    slope[INT_MAX]++;
                }
                else{
                    long double tmp = 1.00*(points[i][1]-points[j][1])/(points[i][0]-points[j][0]);
                    slope[tmp]++;
                }
            }
            int loc_ans = 0;
            for(auto a:slope){
                loc_ans = max(loc_ans, a.second);
            }
            ans = max(loc_ans+same_points, ans);
        }
        return ans;
    }
};

posted on 2022-07-26 03:55  Blackzxy  阅读(16)  评论(0编辑  收藏  举报