当前位置:网站首页>LeetCode 0149. 直线上最多的点数
LeetCode 0149. 直线上最多的点数
2022-08-01 05:23: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
中的所有点 互不相同
方法一:看所有其他点与这个点的斜率
第一层遍历每一个点。
然后,第二层遍历再次遍历每一个点,求出两个点之间的斜率,并用哈希表计数。
因为都经过第一个点,所以斜率相同的点都在一条直线上。
取最大的斜率相同的点的个数,就是经过第一个点的直线中,经过点最多的直线所经过的点。
关于精度问题,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
边栏推荐
- Robot_Framework:常用内置关键字
- Induction jian hai JustFE 2022/07/29 team, I learned the efficient development summary (years)
- LeetCode 1189. “气球” 的最大数量
- 4D line-by-line analysis and implementation of Transformer, and German translation into English (3)
- 深度比较两个对象是否相同
- 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先
- 类神经网络训练不起来怎么办
- 文件的异步读写
- 第6章——数据库的安全性
- Power button (LeetCode) 212. The word search II (2022.07.31)
猜你喜欢
随机推荐
uva12326
Error: AttributeError: module 'matplotlib' has no attribute 'figure'
After the image is updated, Glide loading is still the original image problem
移动应用恶意攻击激增500% 三六零天御为APP免费构建安全屏障
torch
ModuleNotFoundError: No module named 'tensorflow.keras' error message solution
SL-12/2过流继电器
leetcode125 验证回文串
Selenium:操作JS
万字逐行解析与实现Transformer,并进行德译英实战(一)
导致锁表的原因及解决方法
使用string 容器翻转 字母
Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
(2022牛客多校四)H-Wall Builder II(思维)
NDK does not contain any platforms问题解决
Qt Widget 项目对qml的加载实例
权重等比分配
WebSocket实现聊天功能
「游戏引擎 浅入浅出」4.1 Unity Shader和OpenGL Shader
pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)