LeetCode之Max Points on a Line

/*为了确定在一条直线上的点,可以采用斜率进行统计。
对于每个点i,遍历其他所有点,求这些点与i组成的直线的斜率,
斜率相同的点都在一条直线,统计每条直线上点的数目,并获得
他们的最大值。最后取在所有遍历点后,返回这些最大值中最大的数。
方法参考自:https://github.com/soulmachine/leetcode*/
//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.size() < 3) return points.size();

		int res(0);
		map<double, int> slope_count;
		for(int i = 0; i < points.size(); ++i){
			slope_count.clear();
			int samePoint_num(0);
			int point_max(1);//记录经过i的直线,且落在该直线上点最多的数目
			double slope;
			for(int j = i+1; j < points.size(); ++j){
				if(points[i].x == points[j].x){
					if(points[i].y == points[j].y){//与points[i]点是同一点
						++samePoint_num;
						continue;
					}
					else{
						slope = std::numeric_limits<double>::infinity();
					}
				}
				else{
					slope = 1.0*(points[i].y - points[j].y) / (points[i].x - points[j].x);
				}
				int count(0);
				if(slope_count.find(slope) != slope_count.end()){
					count = ++slope_count[slope];
				}
				else{
					count = 2;
					slope_count[slope] = 2;
				}
				point_max = point_max>count ? point_max : count;
			}

			res = res>point_max+samePoint_num ? res : point_max+samePoint_num;
		}
		return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值