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;
}
};
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;
}
};
相关文章推荐
- LeetCode:Max Points on a Line
- Leetcode: Max Points on a Line
- [LeetCode 第5题] -- Max Points on a Line
- 【LeetCode】Max Points on a Line
- #LeetCode Max Points On A Line
- LeetCode || Max Points on a Line
- LeetCode::Max Points on a Line
- [leetcode] 149. Max Points on a Line 解题报告
- LeetCode:Max Points on a Line
- 【leetcode】Max Points on a Line
- LeetCode | Max Points on a Line
- 【leetcode】Max Points on a Line
- Leetcode: 149. Max Points on a Line
- leetcode 149:Max Points on a Line(java实现)细致分析
- Max Points on a Line Leetcode Python
- LeetCode Max Points on a Line
- max-points-on-a-line(Leetcode)
- LeetCode -- Max Points on a Line
- 【leetcode每日一题】149.Max Points on a line
- Max Points On a Line--leetcode