leetcode--001 max point on a line

 package leetcode;

 import java.util.HashMap;

 class Point{
int x;
int y;
Point(){
x=0;
y=0;
}
Point(int a,int b){
x=a;
y=b;
}
} public class MaxPointOnALine {
public static int maxPoints(Point[] points) { if(points.length<=2) {
return points.length;
}
//斜率
double k = 0.0;
int maxPointNum = 0;
int parallelNum =0;
int tempMaxPointNum = 0;
int sameNum=0;
HashMap map=new HashMap<Double,Integer>();
for(int i=0;i<points.length;i++){
sameNum=1;
parallelNum=0;
tempMaxPointNum=0;
map.clear();
for(int j=i+1;j<points.length;j++){
if(points[i].x==points[j].x&&points[i].y==points[j].y){
sameNum++;
}
else if(points[i].x==points[j].x){
parallelNum++; }else {
if(points[i].y==points[j].y){
k=0.0; }else{
k=((double)(points[i].y-points[j].y))/(points[i].x-points[j].x);
}
if(map.get(k)==null){
map.put(k, new Integer(1));
if(1>tempMaxPointNum){
tempMaxPointNum=1;
}
}else{
int number=(int)map.get(k);
number++;
map.put(k, number);
if(number>tempMaxPointNum){
tempMaxPointNum=number;
}
}
}
}
if(parallelNum>1){
if(parallelNum>tempMaxPointNum)
tempMaxPointNum=parallelNum;
}
tempMaxPointNum+=sameNum;
if(tempMaxPointNum>maxPointNum)
maxPointNum=tempMaxPointNum;
}
return maxPointNum;
}
public static void main(String[] args){
Point[] parr = {new Point(1,1),new Point(1,2)};
//maxPoints(parr);
System.out.println(maxPoints(parr));
}
}
上一篇:Java经典面试题


下一篇:Java入门-浅析Java学习从入门到精通【转】