题解 | #多少个点位于同一直线#
多少个点位于同一直线
http://www.nowcoder.com/practice/bfc691e0100441cdb8ec153f32540be2
import java.util.*;
/*
* public class Point {
* int x;
* int y;
* }
*/
public class Solution {
/**
*
* @param points Point类一维数组
* @return int整型
*/
public int maxPoints(Point[] points) {
int res = 0;
// write code here
if (points == null || points.length == 0) {
return 0;
}
if (points.length < 3) {
return points.length;
}
for (int i = 0; i < points.length; i++) {
int duplicatePoint = 1; //重复的点
int vartialPoint = 0; //垂直的点,因为垂直的算不出斜率
Point a = points[i];
HashMap<Float, Integer> map = new HashMap<Float, Integer>();
for (int j = 0; j < points.length; j++) {
if (i == j) {
continue;
}
Point b = points[j];
if (b.x == a.x) { //先算特殊点
if (b.y == a.y) {
duplicatePoint++;
} else {
vartialPoint++;
}
} else { //非特殊点就正常算斜率
float k = (float) (a.y - b.y) / (a.x - b.x); //这里一定要强转一下,否则20组样例只能过13组
if (map.containsKey(k)) {
map.put(k, map.get(k) + 1);
} else {
map.put(k, 1);
}
}
}
int max = vartialPoint;
//先计算有斜率的和垂直的点 的最大数,不包含初始点
for (float k : map.keySet()) {
max = Math.max(map.get(k), max);
}
//后将初始点和重复点,一起加上去
res = Math.max(res, max + duplicatePoint);
}
return res;
}
}