力扣面试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);
	}
}
相关推荐
Blossom.1186 分钟前
把AI“贴”进路灯柱:1KB决策树让老旧路灯自己报「灯头松动」
java·人工智能·python·深度学习·算法·决策树·机器学习
墨染点香2 小时前
LeetCode 刷题【144. 二叉树的前序遍历】
数据结构·算法·leetcode
cynicme7 小时前
力扣3318——计算子数组的 x-sum I(偷懒版)
java·算法·leetcode
im_AMBER10 小时前
算法笔记 09
c语言·数据结构·c++·笔记·学习·算法·排序算法
凯芸呢10 小时前
Java中的数组(续)
java·开发语言·数据结构·算法·青少年编程·排序算法·idea
寂静山林10 小时前
UVa 1030 Image Is Everything
算法
AI柠檬10 小时前
几种排序算法的实现和性能比较
数据结构·算法·c#·排序算法
weixin_4296302611 小时前
第6章 支持向量机
算法·机器学习·支持向量机
SweetCode11 小时前
C++ 实现大数加法
开发语言·c++·算法