LeetCode-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

简明易懂

 

解题思路

 

基本方法

暴力枚举所有的直线(考虑垂直问题和重合问题特判一下)

然后将所有的斜率和截距和点数算出来直接就能给出答案

如果根本不考虑任何的优化的话,复杂度O(n^3)

而且莫名的这样都能过,看来LeetCode根本就没想卡时间

 

改进

注意到直线被截距和斜率唯一的标定了

于是可以为直线建立一个存储结构

算出直线后不遍历所有点得到max_point

而是搜索对应直线,将其经过点数++

注意一些特判就可以

然后这个问题的复杂度就和该结构的插入和查找相关了

 

如果使用了平衡树的话

复杂度应该是O(logn * n^2)

 

如果使用一个hash_map

复杂度就完全可以是O(n^2)

 

//然而标准C++的unordered_map不支持对<double, double>的hash

//真是烦人

//因此下面的代码和我的最初思路不一致一样,不要在意

 

class Solution 
{
public:
    int maxPoints(vector<Point>& points) 
    {
        int res = 0;
        
        if(points.size() <= 2)
        {
            return points.size();
        }
        
        for (int i = 0; i < points.size(); i++) 
        {
            unordered_map<double, int> lineThisTime;
            int vertical_line = 1;
            int same_point = 1;
            for (int j = i + 1; j < points.size(); j++) 
            {
                if (points[i].x == points[j].x) 
                {
                    vertical_line++;
                    if (points[i].y == points[j].y) 
                    {
                        same_point++;
                    }
                    continue;
                }
            
                double k = (double)(points[i].y - points[j].y) / (points[i].x - points[j].x);
                lineThisTime[k] += 1;
            }
            
            res = res < vertical_line ? vertical_line : res;
            
            for (unordered_map<double, int>::iterator it = lineThisTime.begin(); it != lineThisTime.end(); it++)
            {
                res = res < it->second + same_point ? it->second  + same_point: res;
            }
        }
        return res;
    }
};

 

 

 

转载于:https://www.cnblogs.com/ocNflag/p/5042163.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值