LeetCode Max Points on a Line

来源:互联网 发布:苹果cms手机模板安装 编辑:程序博客网 时间:2024/06/13 12:35

题目:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

分析参考:http://www.cnblogs.com/xinsheng/p/3466270.html

/** * 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 n = points.size();if (n == 0)return 0;int res = 1;for (int i = 0; i < n - 1; i++) {unordered_map<double, int> hashmap;int dup = 1, ans = 0;Point p1 = points[i];for (int j = i + 1; j < n; j++) {Point p2 = points[j];//点重复if (p2.x == p1.x && p2.y == p1.y) {dup++;continue;}else if (p2.x == p1.x) {hashmap[INF]++;ans = max(ans, hashmap[INF]);}else {double k = (p2.y - p1.y)*1.0 / (p2.x - p1.x);hashmap[k]++;ans = max(ans, hashmap[k]);}}res = max(res, ans + dup);}return res;}private:const double INF = 1e9;};


0 0
原创粉丝点击