[leetcode] 149. Max Points on a Line 解题报告

46 篇文章 0 订阅

题目链接:https://leetcode.com/problems/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.


思路:又是一个折磨人的题,蛋疼呐!自己写了好久,就是在hash表中以斜率和截距一对为key然后将各点保存起来,谁知道float类型的key对判等有问题。折磨了好久!

后来还是看了别人的思路,要比我的好多了。

代码如下:

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution {
public:
    int maxPoints(vector<Point>& points) {
        int Max = 0, len = points.size();
        for(int i =0; i < len; i++)
        {
            unordered_map<float, int> hash;
            int same =1, vertical =0, curMax=0;
            for(int j =i+1; j < len; j++)
            {
                int x1=points[i].x, y1=points[i].y, x2=points[j].x, y2=points[j].y;
                if(x1 == x2 && y1 == y2) same++;
                else if(x1 == x2) vertical++;
                else curMax = max(curMax, ++hash[(y1-y2)/(1.0*(x1-x2))]);
            }
            Max = max(Max, max(curMax, vertical) + same);
        }
        return Max;
    }
};


参考:https://leetcode.com/discuss/101876/16ms-c-easy-understanding-solution


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值