[leetcode]Max Points on a Line
来源:互联网 发布:php set 编辑:程序博客网 时间:2024/06/07 06:04
Problem Description
Link
在平面图上给出n个点,求最多有多少点在同一条直线上。
Possible Solution
暴力
枚举两个点,固定一条直线。枚举所有点,看有多少点在这条直线上。时间复杂度 O(n^3)
固定一点
固定一个点,枚举其他点,计算斜率,同一个斜率的一定在同一条直线上。复杂度O(n)
统计同一个斜率有多少点的时候,本来想构造一个hash表。后面发现太麻烦了 。其实只需要把每个斜率存下来,然后sort一下, 再判断有多少个重复的k即可。
附代码:
/** * Definition for a point. * struct Point { * int x; * int y; * Point() : x(0), y(0) {} * Point(int a, int b) : x(a), y(b) {} * }; */int ans;int dblcmp(double k) { if (fabs(k)<1e-6) return 0; if (k > 0) return 1; return -1;}class Solution {public: int maxPoints(vector<Point>& points) { int n = points.size(); if (n == 0) return 0; Point &p = points[0]; ans = 0; vector<double> v; int plus = 1; for (int i = 1; i < n; ++i) { Point &x = points[i]; if (x.x == p.x) { if (x.y == p.y) ++plus; else ++ans; } else { double k = double(x.y-p.y)/(x.x-p.x); v.push_back(k); } } std::sort(v.begin(), v.end()); int m = v.size(); for (int i = 0; i < m; ++i) { int j = i; while (i+1 < m && dblcmp(v[i+1] - v[j]) == 0 ) ++i; if (i-j+1 > ans) ans = i-j+1; } return ans+plus; }};
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
- getJSON
- 注解的随记
- 牌型种类
- 怎么使用C#调用C++ dll 类库
- Illegal modifier for parameter *** , only final is permitted”
- [leetcode]Max Points on a Line
- 1. Two Sum
- 在驱动设计的时候出现的error C2509
- Android精仿淘宝/QQ空间标题栏渐变效果
- android使用Charles抓包https请求
- 理解 CSS 属性值语法
- 建立空间索引
- 微信开发之——接口调用频率xianzh
- iOS runtime forwardInvocation一些总结