当前位置:网站首页>LeetCode 0149. Maximum number of points on a line
LeetCode 0149. Maximum number of points on a line
2022-08-01 05:32:00 【Tisfy】
【LetMeFly】149.直线上最多的点数
力扣题目链接:https://leetcode.cn/problems/max-points-on-a-line/
给你一个数组 points
,其中 points[i] = [xi, yi]
表示 X-Y 平面上的一个点.求最多有多少个点在同一条直线上.
示例 1:

输入:points = [[1,1],[2,2],[3,3]] 输出:3
示例 2:

输入:points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] 输出:4
提示:
1 <= points.length <= 300
points[i].length == 2
-104 <= xi, yi <= 104
points
中的所有点 互不相同
方法一:Look at the slope of all other points with this point
The first layer traverses each point.
然后,The second level of traversal traverses each point again,Find the slope between two points,and count with a hash table.
Because they all go through the first point,So points with the same slope are all on a straight line.
Take the maximum number of points with the same slope,It is in the line passing through the first point,The point traversed by the line with the most points.
关于精度问题,C++中使用long double
可以通过.
- 时间复杂度 O ( n 2 ) O(n^2) O(n2),其中 n n n是点的个数
- 空间复杂度 O ( n ) O(n) O(n)
AC代码
C++
long double ONE = 1;
class Solution {
public:
int maxPoints(vector<vector<int>>& points) {
int ans = 0;
int n = points.size();
for (int i = 0; i < n; i++) {
unordered_map<long double, int> ma;
int thisAns = 0;
for (int j = 0 ; j < n; j++) {
if (i == j)
continue;
long double k = ONE * (points[j][1] - points[i][1]) / (points[j][0] - points[i][0]);
ma[k]++;
thisAns = max(thisAns, ma[k]);
}
ans = max(ans, thisAns + 1);
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/126084170
边栏推荐
- Seleniu: Common operations on elements
- 从离线到实时对客,湖仓一体释放全量数据价值
- AspNet.WebApi.Owin 自定义Token请求参数
- 解决浏览器滚动条导致的页面闪烁问题
- 2022年牛客多校第四场补题
- Swastika line-by-line parsing and realization of the Transformer, and German translation practice (a)
- 牛客多校2022第四场A,H,K,N
- 零序电流继电器器JL-8C-12-2-2
- ORACLE 实现另外一个用户修改包(package)
- Causes and solutions of lock table
猜你喜欢
随机推荐
The sword refers to Offer 68 - I. Nearest Common Ancestor of Binary Search Trees
Selenium: element positioning
NUMPY
【FiddlerScript】利用FiddlerScript抓包保利威下载
Dialogue with the father of MySQL: One excellent programmer is worth 5 ordinary programmers
Selenium: Dropdown Box Actions
WebSocket实现聊天功能
Win任务栏图标异常解决
Challenge 52 days to memorize Peppa Pig (Day 01)
2022年牛客多校第四场补题
pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)
Robot_Framework:常用内置关键字
DL-31/6电流继电器
matlab simulink 粒子群优化模糊pid控制的电机泵
WPF项目-按着键盘方向键,移动格子盒子效果
Hunan institute of technology in 2022 ACM training sixth week antithesis
Malicious attacks on mobile applications surge by 500%
flinkcdc对mysql的date字段类型转化有什么解决思路么
WebSocket implements chat function
Qt Widget 项目对qml的加载实例