题目描述
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/**
* 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:
int max(int a,int b){
return a > b?a : b;
}
int maxPoints(vector<Point> &points) {
int size = points.size();
if(size <= 2) return size;
int res = 0;
for(int i =0;i<size;i++){
int d =1;
map<float,int> temp;
for(int j=i+1;j<size;j++){
if(points[i].x == points[j].x){
if(points[i].y == points[j].y ){
d++;
}
else{
temp[INT_MAX]++;
}
}else{
float k = (points[i].y - points[j].y)* 1.0/(points[i].x - points[j].x);
temp[k]++;
}
}
res = max(res, d);
for(auto it= temp.begin(); it!=temp.end();it++)
res = max(res, it->second + d);
}
return res;
}
};思路:在同一二位平面内,分情况讨论:一、两点斜率存在;二、斜率不存在(试探两点是否重复)。
任取一个点,判断这个点与下一个点分类到一、二大类
如果两点斜率存在将斜率作为Key,出现作为value存在一个map中。
如果斜率不存在,那么将共点重合的点出现次数用d变量记录;如果不同点用一个很大的INT_MAX作为Key,出现次数作为value,记录到map中。
变量d,每次换以某基准点(两个点中,第一个点)时候都需要清零,所以应该定义到第一个for循环的作用域内;

京公网安备 11010502036488号