lintcode186. 最多有多少个点在一条直线上

给出二维平面上的n个点,求最多有多少点在同一条直线上。

样例
样例 1:

输入:(1,2),(3,6),(0,0),(1,3).
输出:3
样例 2:

输入:(1,2),(2,3),(3,2).
输出:2
注意事项
x点和y点的坐标值在-1000~1000之间

思路:
原理:经过同一点,斜率相同则在同一直线上
1、利用map记录每一个点斜率出现次数
2、注意两点相同的情况下要重复计点
3、当两点横坐标相同,无斜率情况要注意处理

/**
 * 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:
    /**
     * @param points: an array of point
     * @return: An integer
     */
    int maxPoints(vector<Point> &points) {
        // write your code here
        map<double,int> rates;
        int len=points.size();
        int res=0;
        for (int i = 0; i < len; i++) {
            /* code */
            rates.clear();
            rates[(double)INT_MAX]=1;
            int same=0;
            for (int j = i+1; j < len; j++) {
                /* code */
                if(points[i].x==points[j].x&&points[i].y==points[j].y)
                {
                    same++;
                    continue;
                }
                else if(points[i].x==points[j].x) rates[(double)INT_MAX]++;
                else 
                {
                    double rate=(double)(points[i].y-points[j].y)/double(points[i].x-points[j].x);
                    if(rates.find(rate)!=rates.end()) rates[rate]++;
                    else rates[rate]+=2;
                }
            }
            for (auto count : rates) {
                /* code */
                res=res>count.second+same?res:count.second+same;
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值