LeetCode 149 Max Points on a Line

来源:互联网 发布:网络战略游戏图片 编辑:程序博客网 时间:2024/05/19 04:52

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

在一个平面上有n个点,求一条直线最多能够经过多少个这些点。

Runtime: 10 ms  beats 99.93% of java submissions

public int maxPoints(Point[] points) {int n = points.length;if (n < 2) return n;int currentL, maxL = 2, x, y, dx, dy, overlap = 0, upperB = n;for (int i = 0; i < upperB; i++) {for (int j = i + 1; j < n; j++) {currentL = 1;x = points[i].y - points[j].y;y = points[j].x - points[i].x;if (x == 0 && y == 0) overlap++;else {currentL++;for (int k = j + 1; k < n && currentL + n - k > maxL; k++) {dx = points[k].x - points[i].x;dy = points[k].y - points[i].y;if (x * dx + y * dy == 0)currentL++;}}maxL = Math.max(currentL + overlap, maxL);}upperB = n - maxL;overlap = 0;}return maxL;}
https://discuss.leetcode.com/topic/3991/my-java-accepted-solution-for-your-reference-only-using-array

0 0