最多有多少个点在一条直线上-LintCode

给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例:
给出4个点:(1, 2), (3, 6), (0, 0), (1, 3)。
一条直线上的点最多有3个。
思想:
利用map

#ifndef C186_H
#define C186_H
#include
#include
#include
#include
using namespace std;
struct Point{
    int x;
    int y;
    Point() :x(0), y(0) {}
    Point(int a, int b) :x(a), y(b) {}
};
class Solution {
public:
    /**
    * @param points an array of point
    * @return an integer
    */
    int maxPoints(vector& points) {
        // Write your code here
        int len = points.size();
        if (len <= 2)
            return len;
        map<double, int> m;
        int num= INT_MIN;
        int count = 0;
        for (int i = 0; i < len-1; ++i)
        {
            m.clear();
            int same = 0;
            m[(double)INT_MIN] = 1;
            for (int j = i + 1; j < len; ++j)
            {
                if (points[i].x == points[j].x&&points[i].y == points[j].y)//若亮点相同,则same++
                {
                    same++;
                    continue;
                }
                double rate;
                if (points[j].x - points[i].x == 0)//若斜率无限大,则将值设为INT_MAX
                {
                    rate = INT_MAX;
                }
                else
                {
                    rate = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
                }
                if (m.find(rate) != m.end())//m中存在rate,则加1
                    m[rate] += 1;
                else
                    m[rate] = 2;//若m中不存在,则有两点,加2
            }
            for (auto c : m)
            {
                num = c.second + same > num ? c.second + same : num;
            }
        }
        return num;
    }
};
#endif

你可能感兴趣的:(LintCode)