题目链接:https://leetcode.com/problems/max-points-on-a-line/

题目:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.


思路:

对所有可以配对的点计算他们之间的斜率,并保存。时间复杂度O(n^2),空间复杂度为O(n)。


算法:

public int maxPoints(Point[] points) {
		if (points.length == 0) {
			return 0;
		} else if (points.length == 1) {
			return 1;
		}

		int max = 1;
	
		for (int i = 0; i < points.length; i++) {
			HashMap<Double, Integer> counts = new HashMap<Double, Integer>();// 斜率和该斜率的点的个数
			int x2 = points[i].x, y2 = points[i].y;
			int samePoint = 0;
			int localMax = 1;
			
			for (int j = 0; j < i; j++) {
				int x1 = points[j].x, y1 = points[j].y;
				if (x1 == x2 && y1 == y2) {
					samePoint++;
					continue;
				}
				double a = 0;//斜率
				if (x2 == x1) {
					a = Integer.MAX_VALUE;
				} else {
					a = (double)(y2 - y1) / (double)(x2 - x1); //要将点坐标int强转成double表示斜率
				}
				if (counts.containsKey(a)) {
					counts.put(a, counts.get(a) + 1);
				} else {
					counts.put(a, 2);
				}
			}

			for(Integer n:counts.values()){//遍历跟前面点最多直线的个数
				localMax = Math.max(localMax,n);
			}
			max = Math.max(max, localMax+samePoint);
		}
		return max;
	}