【leetcode】【hard】149. Max Points on a Line

230 篇文章 0 订阅

149. Max Points on a Line

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

Example 1:

Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
|        o
|     o
|  o  
+------------->
0  1  2  3  4

Example 2:

Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
|  o
|     o        o
|        o
|  o        o
+------------------->
0  1  2  3  4  5  6

题目链接:https://leetcode.com/problems/max-points-on-a-line/

解题思路

题目思路与计算回旋镖数量那道题思路一样,关键在于查找表中储存什么。本题储存的是同一个点与其他所有各点的斜率情况统计。

时间复杂度:O(n^2)

空间复杂度:O(n)

几个写代码中的要点:

1.不要忘记垂直的线无法计算斜率。

2.相同点也计数。

3.记录精度有2种方法:

1)直接计算dy/dx:快,但有精度问题。

2)dy和dx除去最大公约数之后记录为分数的字符串:慢,但能储存任何精度。

class Solution {
public:
    int maxPoints(vector<vector<int>>& points) {
        int res=0;
        for(int i=0;i<points.size();++i){
            unordered_map<string,int> record;
            int strait = 0;
            int same=0;
            for(int j=0;j<points.size();++j){
                if(i==j)continue;
                if((points[i][0]==points[j][0])&&(points[i][1]==points[j][1])) same++;
                else if((points[i][0]==points[j][0])&&(points[i][1]!=points[j][1])) strait++;
                else{
                    int dy = points[i][1]-points[j][1];
                    int dx = points[i][0]-points[j][0];
                    int gcd = generateGCD(dx, dy);
                    dx /= gcd;
                    dy /= gcd;
                    string tmp = to_string(dy)+"/"+to_string(dx);
                    record[tmp]++;
                }
            }
            for(auto iter=record.begin();iter!=record.end();++iter){
                res = max(res,iter->second+same+1);
            }
            res = max(res, strait+same+1);
        }
        return res;
    }
    int generateGCD(int a, int b){
        if (b == 0){
            return a;
        } else {
            return generateGCD(b, a % b);
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值