问题来自http://oj.leetcode.com/problems/max-points-on-a-line/
Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
问题定义为给定2维平面上N个点,找到处于同一直线上的最大点的数目。包括横竖线以及斜线。
思路:N个点,任意两点为一线,最多N^2条直线,处于同一直线的所有点的斜率相同。因此对所有的直线求得其斜率,并进行计数,找到最大。
#include <iostream>
#include <vector>
#include <limits>
#include <map>
using namespace std;
/*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 maxPoints(vector<Point> &points) {
if(points.size() <=2)
return points.size();
else{
//N^2解法 求斜率slope并对其计数
int maxPoints = 1;
for(vector<Point>::size_type i = 0; i < points.size(); i++){
Point pi = points[i];
//same with pi
int maxSameWithI = 0;
//map
map<double, int> slope_count;
for(vector<Point>::size_type j=i+1; j < points.size(); j++){
Point pj = points[j];
double slope = 0.0;
if(pi.x != pj.x){
slope = (double)(pj.y-pi.y)/(double)(pj.x-pi.x);
slope_count[slope]++;
}
else if(pi.y==pj.y){
maxSameWithI++;
}
else{
slope = numeric_limits<double>::max();
slope_count[slope]++;
}
}
//find max
int max = maxSameWithI+1;
if(slope_count.size()!=0){
int maxSlopes = 0;
for(map<double,int>::iterator it = slope_count.begin(); it!=slope_count.end(); it++){
if(it->second > maxSlopes)
maxSlopes = it->second;
}
max += maxSlopes;
}
if(max > maxPoints)
maxPoints = max;
}
return maxPoints;
}
}
};
int main(int argc, char** argv){
Solution s;
vector<Point> points;
Point p1(2,1);
points.push_back(p1);
Point p2(1,2);
points.push_back(p2);
Point p3(1,-1);
points.push_back(p3);
Point p4(2,0);
points.push_back(p4);
Point p5(3,-1);
points.push_back(p5);
Point p6(3,1);
points.push_back(p6);
Point p7(0,-2);
points.push_back(p7);
cout<<"maxPoints : "<<s.maxPoints(points)<<endl;
return 0;
}
注:i 确定之后,与 i 相连的所有直线的斜率计算之后不再重复计算。