Max Points on a Line--LeetCode
来源:互联网 发布:塞尔维亚知乎 编辑:程序博客网 时间:2024/06/07 05:18
1.题目
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.题意
计算几何,给定一个点集合,求最大的共线点的个数
3.分析
找出相同点和相同斜率的点
通过斜率来判断共线需要用到除法
用double表示的双精度小数在有的系统里不一定准确
为了精确无误的计算,应当避免除法,避免无线不循环小数的出现
可将两数分别除以它们的最大公约数,pair作为key
gcd采用算法导论中的欧几里德算法
注意两个max函数要放在外层循环,不要忘记return res;
4.代码
/** * 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 res = 0; for(int i = 0; i < points.size(); ++i) { int duplicate = 1; map<pair<int, int>, int> m; for(int j = i + 1; j < points.size(); ++j) { if(points[j].y == points[i].y && points[j].x == points[i].x) ++duplicate; else { int dy = points[j].y - points[i].y; int dx = points[j].x - points[i].x; int d = gcd(dx, dy); ++m[{dx/d, dy/d}]; } } res = max(res, duplicate); for(auto it = m.begin(); it != m.end(); ++it) res = max(res, it->second + duplicate); } return res; }private: int gcd(int a, int b) { if(b == 0) return a; else return gcd(b, a % b); }};
阅读全文
0 0
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- 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] Max Points on a Line
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- leetcode:【Max Points on a Line】
- Max Points on a Line - LeetCode
- 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
- 写一个简单的静态商城页面注意点(个人随笔)
- 让马云秒变程序猿的REST Client工具你弄么?
- Vue(使用webpack)与java后端(使用springmvc与tomcat8)整合测试与部署方案
- HTML左图右字
- view 图像可鼠标按住移动
- Max Points on a Line--LeetCode
- 大话数据结构
- Tour UVA
- 顺序队中实现队列的基本运算
- GMS 包配置说明
- hdu4343 Interval query【贪心+倍增】
- 编程判断100以内的完数
- 应该这样理解Android MVP
- 所有心得