Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路: 从 points[] 中依次取出一个点,然后依次和后面一个点组成一条直线。 y = ax+b;
然后再遍历所有的点看是否满足当前的斜率a 和 截距 b。 如果满足count++。维护一个max, 每次遍历完将count和max比较取最大.
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ public class Solution { public int maxPoints(Point[] points) { if(points == null || points.length == 0) return 0; int len = points.length; int max = 1; for(int i = 0; i < len; i++){ Point point1 = points[i]; for(int j = i+1; j<len; j++){ Point point2 = points[j]; int count = 0; if(point1.x == point2.x){ for(int z = 0; z < len; z++){ if(points[z].x == point1.x) count++; } }else{ double x1 = point1.x; double y1 = point1.y; double x2 = point2.x; double y2 = point2.y; double a = (y1 - y2) / (x1 - x2); // 这里的b 是根据 y1 = ax1+b 和 y2 = ax2+b 求出来的 double b = (y1 * x2 - y2 * x1) / (x2 - x1); for(int z = 0; z < len; z++){ if(Math.abs(points[z].x * a + b - points[z].y) < 0.000001) count++; } } if(count > max) max = count; } } return max; } }