力扣面试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);
	}
}
相关推荐
hn小菜鸡3 分钟前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
Deepoch37 分钟前
Deepoc 大模型:无人机行业的智能变革引擎
人工智能·科技·算法·ai·动态规划·无人机
心平愈三千疾1 小时前
通俗理解JVM细节-面试篇
java·jvm·数据库·面试
漂流瓶jz2 小时前
清除浮动/避开margin折叠:前端CSS中BFC的特点与限制
前端·css·面试
我不吃饼干9 天前
鸽了六年的某大厂面试题:你会手写一个模板引擎吗?
前端·javascript·面试
我不吃饼干9 天前
鸽了六年的某大厂面试题:手写 Vue 模板编译(解析篇)
前端·javascript·面试
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
前端fighter9 天前
为什么需要dependencies 与 devDependencies
前端·javascript·面试
前端fighter9 天前
Vuex 与 Pinia:全面解析现代 Vue 状态管理的进化之路
前端·vue.js·面试