125_leetcode_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.

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;
        
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章