LeetCode | Max Points on a Line
2013-12-11 13:31
453 查看
题目:
Given n pointson 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) { if(points.size() <= 2){ return points.size(); } int max = 2; int cur = 1; for(int i = 0; i < points.size(); i++){ int duplicate = 0; for(int j = i + 1; j < points.size(); j++){ if(points[i].x == points[j].x && points[i].y == points[j].y){ duplicate++; continue; } cur++; for(int k = j + 1; k < points.size(); k++){ if(sameLine(points[i], points[j], points[k])){ cur++; } } if(cur + duplicate > max){ max = cur + duplicate; } cur = 1; } if(cur + duplicate > max){ max = cur; } cur = 1; } return max; } bool sameLine(Point p1, Point p2, Point p3){ return (p2.y - p3.y) * (p1.x - p3.x) == (p1.y - p3.y) * (p2.x - p3.x); } };
相关文章推荐
- LeetCode Max Points on a Line 解题报告
- [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习题: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 149. Max Points on a Line
- [LeetCode]题解(python):149-Max Points on a Line
- Leetcode 149 Max Points on a Line
- Max Points on a Line--LeetCode
- 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 149. Max Points on a Line
- LeetCode_149maxPoints [Max Points on a Line]