Max Points on a Line
来源:互联网 发布:软考程序员 编辑:程序博客网 时间:2024/06/05 07:42
Max Points on a Line
leetcode
Max Points on a Line
题目链接
题目大意:
给定一些点(二维)的集合, 找出位于同一条直线的点的个数的最大值
Code
reference
/**
* 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) {
double slope;
int maxNum = 0;
double nSlope;
int size = points.size();
// if the number of the points is less than 3
// then directly return it
// since more than 1 point makes a line
if(size < 3) {
return size;
}
for(int i = 0; i < size; i++) {
int rep = 0;
// slope -> count
std::map<double, int> lines;
for(int j = 0; j < size; j++) {
if(i == j) {
continue;
}
// replication
if(points[i].x == points[j].x
&& points[i].y == points[j].y) {
rep++;
continue;
}
// x1 == x2
// in this case, it can compute the slope
// which is oo (infinity)
// so use INT_MIN or INT_MAX to record this case
// here use INT_MIN
if(points[i].x == points[j].x) {
lines[INT_MIN]++;
} else {
slope = (points[i].y - points[j].y)
/ (points[i].x - points[j].x + 0.);
lines[slope]++;
}
}
// statistic & maybe lines is empty
if(lines.size() == 0) {
maxNum = max(maxNum, rep);
continue;
}
// statistic
std::map<double, int>::iterator iter;
for(iter = lines.begin(); iter != lines.end(); iter++) {
if(iter->second + rep > maxNum) {
maxNum = iter->second + rep;
nSlope = iter->first;
}
}
}
// don't forget that plus the point itself
return maxNum + 1;
}
};
0 0
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points On a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- max points on a line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- Max Points on a Line
- 第十四周项目二 带姓名的成绩单(数据由score.txt提供)
- Skyline查询实验数据点的生成
- 编译qt2.2的问题
- 【微信公众平台应用开发实践】API详解--基础接口
- 第14周项目3-(1)(2)
- Max Points on a Line
- 第14周 项目2-带姓名的成绩单(1)
- [windows phone开发]锁屏背景
- 哈希函数的构造方法
- php5.4后htmlspecialchars输出为空的问题
- 决策树学习
- Git-06_分支
- java反射
- IOS开发之UI控件属性