您的位置:首页 > 其它

LEETCODE: Max Points on a Line

2015-01-11 22:33 435 查看
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 maxPoints(vector<Point> &points) {
unordered_map<float, int> map;
int maxNum = 0;
for(int ii = 0; ii < points.size(); ii ++) {
map.clear();
map[INT_MIN] = 0;
int duplicate = 1;
for(int jj = 0; jj < points.size(); jj ++) {
if(jj == ii) continue;
if(points[ii].x == points[jj].x && points[ii].y == points[jj].y) {
duplicate ++;
continue;
}
float k = points[ii].x == points[jj].x ? INT_MAX : (float)(points[jj].y - points[ii].y) / (points[jj].x - points[ii].x);
map[k] ++;
}
auto it = map.begin();
for(; it != map.end(); it ++) {
if(it->second + duplicate > maxNum) {
maxNum = it->second + duplicate;
}
}
}
return maxNum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息