思路跟leetcode的答主的相似,代码能力不好,写不出来,然后参考leetcode上的博主的:直接copy过来了
思路
遍历每个点,通过斜率相等判断是否与其它点在同一条直线上。分为三种情况:
相同点
x点坐标相同,即与x轴垂直
正常求斜率
注意:long double防止精度丢失
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int res=0;
int n=points.size();
for(int i=0;i<n;++i)
{
unordered_map<long double,int>unmap;
int samePoint=1;
for(int j=i+1;j<n;++j)
{
if(points[i][0]==points[j][0]&&points[i][1]==points[j][1])
{
++samePoint; //相同点
}
else if(points[i][0]==points[j][0])
{
++unmap[INT_MAX]; //x点坐标相同,即与x轴垂直
}
else
{
long double slope=(long double)(points[i][1]-points[j][1])/(points[i][0]-points[j][0]);
++unmap[slope]; //正常求斜率 ++unmap[slope]就已经是对int(value)进行计数求值
}
}
int localMax=0;
for(auto iter=unmap.begin();iter!=unmap.end();++iter)
{
// localMax=(localMax,unmap->second());
localMax=max(localMax,iter->second);
}
localMax +=samePoint; //加上相同点数
res=max(res,localMax);
}
return res;
}
};
注意点:
1.C++最大值:INT_MAX
2.c++中map与unordered_map的区别:
map:具有自动排序的功能
unordered_map:内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的
3.++unmap[slcope]也就是对++unmap[key]进行计数,其value值一直在增加
4.unordered_map<long double,int>::iter iter->second这个语句是对value进行取值