首页 技术 正文
技术 2022年11月15日
0 收藏 413 点赞 2,886 浏览 1269 个字
//定义二维平面上的点
struct Point
{
int x;
int y;
Point(int a=, int b=):x(a),y(b){}
};
bool operator==(const Point& left, const Point& right)
{
return (left.x==right.x && left.y==right.y);
}

//求两个点连接成的直线所对应的斜率
double line_equation(const Point& P1, const Point& P2)
{
double slope;
if(P1.x==P2.x)
slope = 1e+;
else
slope = double(P1.y-P2.y)/(P1.x-P2.x);
return slope;
}class Solution {
public:
int maxPoints(vector<Point> &points)
{
int max=;
for(vector<Point>::iterator it=points.begin(); it!=points.end(); ++it)
{
map<double, int> Line_count;
int same_count=; //same_count表示同一个点重复出现的个数 for(vector<Point>::iterator it2=it; it2!=points.end(); ++it2) //此处it2=points.begin()还是it2=it虽然不影响最终结果,但是对于时间复杂度影响很大,it2=it的时间复杂度要低很多
{
if(*it==*it2)
{
++same_count;
continue;
}
double slope = line_equation(*it, *it2);
++Line_count[slope];
}
set<int> iset;
for(map<double, int>::iterator iter = Line_count.begin(); iter!=Line_count.end(); ++iter)
iset.insert(iter->second);
int max_now = same_count;
if(iset.begin()!=iset.end())
max_now = same_count + *(--iset.end());
if(max_now>max)
max = max_now;
}
return max;
}
};

问题描述:在一个二维平面上有n个点,求出现在同一直线上的点的最大个数

分析:对每一个点计算与其他点(不包括与该点相同的点)连接成的直线的斜率,斜率重复出现的最大次数加成该点重复出现的个数,即为该点所在直线上拥有的最大点个数(比如该点既出现在直线L1上,又出现在直线L2上,直线L1上有这n个点中的3个点,直线L2上有这n个点中的5个点,我们得到的该点所处直线的拥有最多点的那一条直线上的点个数便是5,有点绕口~~)。

对每一个点进行相同的操作,便可得到n个点中出现在同一直线的点的最大个数。

只需考虑斜率就可以解决这个问题,之前考虑还需要截距,其实完全不必要,不要把问题想得太复杂~

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294