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

题目链接: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) {
        unordered_map<float, int> hash;
        int Max = 0;
        for(int i = 0; i< points.size(); i++)
        {
            hash.clear();
            int tem = 0, same = 1, vertical = 0;
            for(int j = i+1; j< points.size(); 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 tem = max(tem, ++hash[(float)(y1-y2)/(x1-x2)]);
            }
            Max = max(Max, max(vertical, tem)+same);
        }
        return Max;
    }
};
参考:https://leetcode.com/discuss/101876/16ms-c-easy-understanding-solution


你可能感兴趣的:(Math,LeetCode)