最多有多少个点在一条线上
问题描述
给出二维平面上的n个点,求最多有多少点在同一条直线上。
样例
样例1:
输入:(1,2),(3,6),(0,0),(1,3).
输出:3
样例2
输入:(1,2),(2,3),(3,2).
输出:2
大致思想:
使用一个Map来存放已经出现过的斜率,要注意相同的点,分母为0的点,
这里采用字符串的方式来记录斜率,可以有效规避分母为0的情况,比如
“5_2”代表斜率为5/2
Java代码
/**
* 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 {
/**
* @param points: an array of point
* @return: An integer
*/
public int maxPoints(Point[] points) {
// write your code here
if (points == null || points.length == 0)
return 0;
int ans = 0;
int len = points.length;
for (int i = 0; i < len; i++) {
Map<String, Integer> map = new HashMap<>();
int dup = 1;
for (int j = i+1; j < len; j++) {
if(points[i].x == points[j].x && points[i].y == points[j].y) {
dup++;
continue;
}
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
int g = gcd(dx, dy);
String temp = "" +dx/g+"/"+dy/g;
if (map.containsKey(temp)) {
map.put(temp, map.get(temp) + 1);
} else {
map.put(temp, 1);
}
}
ans = Math.max(ans, dup);
for (int a : map.values()) {
ans = Math.max(ans , dup + a);
}
}
return ans;
}
private int gcd(int a, int b) { //求最大公因数,辗转相除法
if (b == 0) return a;
return gcd(b, a%b);
}
}