力扣面试150 直线上最多的点数 数学 直线斜率 欧几里得求最大公约数

Problem: 149. 直线上最多的点数

思路

👨‍🏫 参考题解

💖 枚举直线 + 枚举统计

时间复杂度: O ( n 3 ) O(n^3) O(n3)

空间复杂度: O ( 1 ) O(1) O(1)

Java 复制代码
class Solution {
	public int maxPoints(int[][] points)
	{
		int n = points.length;
		int ans = 1;
		for (int i = 0; i < n; i++)
		{
			int[] a = points[i];// 点1
			for (int j = i + 1; j < n; j++)
			{
				int[] b = points[j];// 点2
				int cnt = 2;
				for (int k = j + 1; k < n; k++)
				{
					int[] c = points[k];// 枚举其他的点
//					int s1 = (b[1] - a[1]) * (c[0] - b[0]);
//					int s2 = (c[1] - b[1]) * (b[0] - a[0]);
					int s1 = (a[1] - b[1]) * (b[0] - c[0]);
					int s2 = (a[0] - b[0]) * (b[1] - c[1]);
					if (s1 == s2)
						cnt++;
				}
				ans = Math.max(cnt, ans);
			}
		}
		return ans;
	}
}

枚举直线 + 哈希表统计


java 复制代码
class Solution {
//	枚举直线 + 哈希表统计
	public int maxPoints(int[][] points)
	{
		int n = points.length, ans = 1;
		for (int i = 0; i < n; i++)
		{
			Map<String, Integer> map = new HashMap<>();
			// 由当前点 i 发出的直线所经过的最多点数量
			int max = 0;
			int x1 = points[i][0], y1 = points[i][1];
			for (int j = i + 1; j < n; j++)
			{
				int x2 = points[j][0], y2 = points[j][1];
				int xx = x1 - x2, yy = y1 - y2;
				int k = gcd(xx, yy);// 最大公约数
				String key = (xx / k) + "_" + (yy / k);// 化简
				map.put(key, map.getOrDefault(key, 0) + 1);// key 是斜率,value 是数量
				max = Math.max(max, map.get(key));
			}
			ans = Math.max(ans, max + 1);
		}
		return ans;
	}
    //	求最大公约数
	int gcd(int a, int b)
	{
		return b == 0 ? a : gcd(b, a % b);
	}
}
相关推荐
文丑颜不良啊21 分钟前
LeetCode3101~3120题目解析
java·leetcode
ShineWinsu39 分钟前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
kyle~4 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯5 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好6 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘7 小时前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程8 小时前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊8 小时前
LeetCode3061~3080题目解析
java·leetcode
时间的拾荒人10 小时前
Redis 典型应用:缓存与分布式锁原理
redis·分布式·缓存·面试·架构
电科_银尘10 小时前
【大模型算法与工程 01】机器学习的问题定义:监督、无监督、自监督与强化学习
人工智能·算法·机器学习