LC-多少个点位于同一直线

多少个点位于同一直线

//max points on a line
//对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
#include<vector>
#include<iostream>
#include<map>
using namespace std;

struct Point {
	int x;
	int y;
};

class Solution {
public:
	/**
	*
	* @param points Point类vector
	* @return int整型
	*/
	//采用map<float,int>计量相同斜率的一组点的数目
	//map的实值+与当前点i重复点个数(若无重复点即为1)即为所求当前斜率下最多共线点数
	//INT_MAX 表示斜率为无穷大的情况
	//若两点位置相同,也为共线点,以repeatCount量表示位置相同点的组的数目
	int max(int a, int b)
	{
		return a > b ? a : b;
	}

	int maxPoints(vector<Point>& points) {
		int pointSize = points.size();
		if (pointSize <= 2)
			return pointSize;
		int count = 0;
		for (int i = 0; i < pointSize-1; ++i)
		{
			map<float, int> kmap;
			int repeatCount = 1;
			for (int j = i + 1; j < pointSize; ++j)
			{
				if (points[i].x == points[j].x)
				{
					if (points[i].y == points[j].y)       //若两点位置相同,记录
					{                                     //重复点数
						repeatCount++;
					}
					else                                  //若斜率为无穷大,
					{                                     //以INT_MAX表示
						kmap[INT_MAX]++;
					}
				}
				else
				{
					float k = (points[i].y - points[j].y)*1.0 / (points[i].x - points[j].x);
					kmap[k]++;
				}
			}
			count = max(count, repeatCount);
			for (auto rk : kmap)
			{
				count = max(count, rk.second + repeatCount);
			}
		}
		return count;
	}
	
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值