问题描述
对于给定的n个位于同一二维平面上的点,求最多能有多少个点位于同一直线上
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
输入的point的结构为:
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
解决方案
这题基本的框架是穷举:针对每个点,穷举剩下的点的所有可能性。
有几点是这道问题中需要注意的:
- 使用斜率作为一条直线上的所有可能性的穷举。应当考虑斜率为无穷(垂直情况)和两点重合情况。
- 计算斜率时float和double可能出现精度不够或出现无穷小数的情况,这样在使用斜率的map时会出现问题(一开始使用double计算斜率有几例不能通过)。使用斜率的分子分母公约数pair对替代斜率作为map的key可以避免小数计算时的问题。map定义为map<map<int,int>,int>。
#include <vector>
#include <algorithm>
#include <map>
class Solution {
public:
int maxPoints(vector<Point> &points) {
int size = points.size();
int max_count=0;
if(size==0)return 0 ;
if(size==1)return 1;
for(int i = 0;i<size;i++){
int x_temp=points[i].x,y_temp=points[i].y;
int count_row=0,extra_count=0;
int max_temp=0;
map<map<int,int>,int>k;
for(int j=0;j<points.size();j++){
int x = points[j].x,y=points[j].y;
if(x==x_temp&&y==y_temp){
extra_count++;
max_temp=max(max_temp,extra_count);
}
else {
if(x==x_temp && y!=y_temp){
count_row++;
max_temp = max(max_temp,count_row+extra_count);
}
else{
int gapx= x-x_temp;
int gapy = y-y_temp;
map<int,int>k_temp;
int d = std::__gcd(gapx,gapy);
k_temp[gapy/d]=gapx/d;
map<map<int,int>,int>::iterator iter;
iter = k.find(k_temp);
if(iter==k.end()){
k[k_temp]=1;
}
else{
k[k_temp]++;
}
max_temp=max(max_temp,k[k_temp]+extra_count);
}
}
}
max_count=max(max_count,max_temp);
}
return max_count;
}
};