Max Points on a Line
通过计算斜率来判断是否在一条直线上,要注意首尾点可能重复,另外java double类型的 0 和 -0是不一样的,最后O(n平方)过了,O(2n平方)超时了,public class Solution {
public int maxPoints(Point[] points) {
int result = 0;
HashMap<Double,Integer> v = new HashMap<Double,Integer>();
for(int i = 0; i < points.length ; ++i){
int total = 0;
int special = 0;
int multiple = 1;
for(int j = i+1 ; j < points.length ; ++j){
if(points[j].x != points[i].x ){
double ratio = (double)(points[j].y - points[i].y)/(double)(points[j].x - points[i].x);
if((Math.abs(ratio) - 0) < 0.0000001){
ratio = 0d;
}
v.put(ratio,v.get(ratio) == null?1:v.get(ratio)+1);
int size = v.get(ratio);
if(total < size ){
total = size;
}
}else if(points[j].x == points[i].x && points[j].y != points[i].y){
special ++;
}else{
multiple ++;
}
}
v.clear();
if(result < special + multiple){
result = special + multiple;
}
if(result < total + multiple){
result = total + multiple;
}
}
return result;
}
}
public class Solution {
public int maxPoints(Point[] points) {
int result = 0;
HashMap<Double,Integer> v = new HashMap<Double,Integer>();
for(int i = 0; i < points.length ; ++i){
int total = 0;
int special = 0;
int multiple = 1;
for(int j = i+1 ; j < points.length ; ++j){
if(points[j].x != points[i].x ){
double ratio = (double)(points[j].y - points[i].y)/(double)(points[j].x - points[i].x);
if((Math.abs(ratio) - 0) < 0.0000001){
ratio = 0d;
}
v.put(ratio,v.get(ratio) == null?1:v.get(ratio)+1);
int size = v.get(ratio);
if(total < size ){
total = size;
}
}else if(points[j].x == points[i].x && points[j].y != points[i].y){
special ++;
}else{
multiple ++;
}
}
v.clear();
if(result < special + multiple){
result = special + multiple;
}
if(result < total + multiple){
result = total + multiple;
}
}
return result;
}
}