天天看点

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.

思路:穷举法,双层循环,用map实现

不过需要注意的一点,不要忘记点是重复的点,以及考虑斜率无穷大的情况

代码:

/**
 * 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) {
        if(points.empty())
            return ;
        unordered_map<float,int> mp;
        int max_num = ;
        for(int i = ;i < points.size();i++){            
            mp.clear();
            mp[INT_MAX] = ;
            int duplicated = ;
            for(int j = i+;j < points.size();j++){
                if(points[i].x==points[j].x && points[i].y==points[j].y){//重复点
                    duplicated++;
                    continue;
                }
                //如果没有进上面的if,说明不是重复点,x又相等的话,斜率无穷大
                float k =  points[i].x==points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points

[j].x - points[i].x);
                mp[k]++;
            }
            for(unordered_map<float,int>::iterator mit = mp.begin();mit!=mp.end();mit++){
            if(mit->second + duplicated > max_num)//需要重复点和计数加起来作为这条斜率上的点
                max_num = mit->second + duplicated;
            }

        }
        return max_num;
    }

};