125_leetcode_Max Points on a Line

来源:互联网 发布:php函数手册 编辑:程序博客网 时间:2024/06/06 01:07

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

1:注意特殊情况, 点的个数为1,2, 0的时候;2:设置map unordered_map<float, int> 用于保存相应斜率的点的个数;3:两个点重合,两个点的斜率不存在, 以及两个点斜率正常的情况;4:在统计某个斜率的个数的时候注意点重合的情况;

        int maxPoints(vector<Point> &point)    {        if(point.size() <= 2)        {            return (int)point.size();        }                int maxNumber = 2;        unordered_map<float, int> result;                int size = (int)point.size();        int duplicates = 0;                for(int i = 0; i < size; i++)        {            duplicates = 1;            result.clear();                        for(int j = 0; j < size; j++)            {                if (i == j)                {                    continue;                }                                if(point[i].x == point[j].x && point[i].y == point[j].y)                {                    duplicates += 1;                }                else if(point[i].x == point[j].x)                {                    result[INT_MAX]++;                }                else                {                    float k = ((float)point[j].y - (float)point[i].y) / (point[j].x - point[i].x);                    result[k]++;                }            }                        unordered_map<float, int> ::iterator itr = result.begin();            maxNumber = maxNumber < duplicates ? duplicates : maxNumber;            for(; itr != result.end(); itr++)            {                if( itr->second + duplicates > maxNumber)                {                    maxNumber = itr->second + duplicates;                }            }        }        return maxNumber;            }


0 0
原创粉丝点击