max-points-on-a-line
题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
给出n个点的坐标,找出在一条线上的点的数量的最大值.
根据斜率统计在一条直线上的点的数量,可以用HashMap作为斜率和数量的映射
注意分析各种情况。相同的点单独统计。横坐标相同的点可以手动分配一个不容易出现的斜率。
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int maxPoints(Point[] points) {
int result = 1;
int length = points.length;
if (length <= 2)
return length;
for (int i = 0; i < length; i++) {
int tmpCount = 0;
Map<Float, Integer> map = new HashMap<Float, Integer>();
int val = 1;
int max = 0;
for (int j = 0; j < length; j++) {
if (i != j) {
int temp = 0;
if (points[i].x == points[j].x
&& points[i].y == points[j].y) {
tmpCount++;
} else {
val = 1;
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
if (dx == 0) {
if (map.containsKey(100000f)) {
val = map.get(100000f);
}
val++;
map.put((float) 100000, val);
}else{
float k = (float)dy/(float)dx;
if(map.containsKey(k)){
val = map.get(k);
}
val++;
map.put(k, val);
}
if(max<val) max = val;
}
}
}
if(max==0) max =1;
tmpCount+=max;
if(tmpCount>result) result = tmpCount;
}
return result;
}
}