package code;
import org.junit.Assert;
import java.util.*;
/**
* @author wanqilin
* @date 2019/5/6
* @description
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
Explanation:
^
|
| o
| o
| o
+------------->
0 1 2 3 4
Example 2:
Input: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4
Explanation:
^
|
| o
| o o
| o
| o o
+------------------->
0 1 2 3 4 5 6
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
kx0 + b = y0;
kx1 + b = y1;
k(x0 - x1) = (y0 - y1);
k = (y0 - y1) / (x0 - x1) = y / x;
why x and y can be represented the straight line ?
because not just y and x are represented the line,the started point represent too.
*/
public class MaxPointsOnALine {
public static void main(String[] args) {
int[][] points = new int[6][2];
points[0][0] = 1;
points[0][1] = 1;
points[1][0] = 3;
points[1][1] = 2;
points[2][0] = 5;
points[2][1] = 3;
points[3][0] = 4;
points[3][1] = 1;
points[4][0] = 2;
points[4][1] = 3;
points[5][0] = 1;
points[5][1] = 4;
Assert.assertEquals(4,maxPoints(points));
}
private static int maxPoints(int[][] points) {
if (points==null) return 0;
if (points.length<=2) return points.length;
Map<Long,Integer> counter = new HashMap<>();
int len = points.length;
int max = 0;
for (int i = 0; i < len; i++) {
int overlap = 0;
int max0 = 0;
for (int j = i + 1; j < len; j++) {
int x = points[i][0] - points[j][0];
int y = points[i][1] - points[j][1];
if (x == 0 & y == 0){
overlap++;
continue;
}
int gcd = getGCD(x,y);
Long hash = (((long) x / gcd) << 32) | (y/gcd);
int c = counter.getOrDefault(hash,0) + 1;
counter.put(hash,c);
max0 = Math.max(max0,c);
}
max = Math.max(max0 + overlap + 1,max);
counter.clear();
}
return max;
}
/**
* 求最大公约数(辗转相余法)
* 设 x,y (x >= y)
* x = su (u为公约数)
* y = tu
* x = dy + r (r为余数)
* su = dtu + r
* r = (s - dt)u (证明 x,y的公约数也是r的约数)
* 那么带入下面的函数
* x%y = r 的约数是x,y的公约数
* 当r = 0时表示y是最大公约数 则返回
*
*/
private static int getGCD(int x, int y) {
if (y == 0) return x;
return getGCD(y,x%y);
}
}
网友评论