您的位置:首页 > 编程语言 > C语言/C++

leetcode #149 in cpp

2016-06-28 10:59 330 查看
Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.

Solution: 

 three points,p1,p2,p3, are on the same line if and only if slope(p2) == slope(p3) where slope of pi is defined as (pi.y - p1.y)/
(pi.x - p1.x). 

Think about it in the other way. If p2 has the same slope as p3 does with respect to p, then p, p3, p2 would be on the same
line. 

algorithm:

for each point p

create a map collecting slope with respect to p

 for other point pi

calculate the slope(pi) with respect to p;

    increase map[slope(pi)] ( map[slope(pi)] represents the total number of points with slope(pi) with respect to p )

find the max number in the map. 

Code:

/**
* 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) {
int maxPoint = 0;
int x;
int y;
float slope;
map<float,int> slopes;

for(int i = 0; i < points.size(); i ++){
slopes.clear(); //collect slopes of point i+1...n with respect to points[i]
x = points[i].x;
y = points[i].y;
int temp_max = 1;
for(int j = i + 1; j < points.size(); j ++){
if(points[j].x == x && points[j].y == y){//if the same point
temp_max++;
continue;
}
//if not the same point, calculate slope and add 1 to the corresponding entry
slope = points[j].x - x == 0 ?INT_MAX:float(points[j].y - y )/(points[j].x -x);
if(slopes.find(slope) == slopes.end()){
slopes[slope] = 1;
}else{
slopes[slope] ++;
}
}
maxPoint = max(maxPoint, temp_max); //compare num of points[i] in the input first.
//this is because if the input contains only points[i]
// we wont go into the loop to find the max point
for(auto it = slopes.begin(); it!=slopes.end(); ++it){
maxPoint = max(maxPoint, it->second + temp_max );
}
}

return maxPoint;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cpp leetcode