力扣面试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);
	}
}
相关推荐
技术小泽1 小时前
OptaPlanner入门以及实战教学
后端·面试·性能优化
leiming62 小时前
c++ map容器
开发语言·c++·算法
杨校2 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog2 小时前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing20192 小时前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人
谈笑也风生3 小时前
把二叉搜索树转换为累加树(一)
算法
youngee113 小时前
hot100-64跳跃游戏
算法·游戏
POLITE34 小时前
Leetcode 19. 删除链表的倒数第 N 个结点 JavaScript (Day 11)
javascript·leetcode·链表
liu****4 小时前
机器学习-线性回归
人工智能·python·算法·机器学习·回归·线性回归