Max Points on a Line

来源:互联网 发布:数组是线性表吗 编辑:程序博客网 时间:2024/05/17 05:51
这道题做不出来的原因是,斜率不会比较(精度问题)。
下面的代码是网上的方法,用的是unordered_map,相当于一个hash索引,所以不会有精度问题。
过些天再做这个题,看能不能扁出来

/** * 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) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.        int len = points.size(), res = 1;        if(len == 0)return 0;        unordered_map<double, int> umap;        for(int i = 0; i < len; i++)        {            umap.clear();            int samePointNum = 0,tmpres = 1;            for(int j = i+1; j < len; j++)            {                double slope = std::numeric_limits<double>::infinity();//斜率                if(points[i].x != points[j].x)                    slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);                else if(points[i].y == points[j].y)                    {samePointNum++; continue;}                int tmp;                if(umap.find(slope) != umap.end())                    tmp = ++umap[slope];                else                 {                    umap.insert(unordered_map<double, int>::value_type(slope, 2));                    tmp = 2;                }                if(tmpres < tmp)tmpres = tmp;            }            if(res < tmpres + samePointNum)res = tmpres + samePointNum;        }        return res;    }};

0 0