您的位置:首页 > 其它

leetcode--max-points-on-a-line

2018-02-11 18:43 411 查看

描述

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

代码

/**
* 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.*;
public class Solution {
public int maxPoints(Point[] points) {
if(points.length==0){
return 0;
}
if(points.length==1){
return 1;
}
int max=0;
for(int i=0;i<points.length;i++){
Map<Double,Integer> map=new HashMap<>();
Map<Point,Integer> exi=new HashMap<>();
exi.put(points[i],1);
for(int j=0;j<points.length;j++){
if(i!=j){
Integer temp=exi.get(points[j]);
if(points[i].y==points[j].y&&points[i].x==points[j].x){
Integer count=exi.get(points[i]);
exi.put(points[i],count+1);
if(exi.get(points[i])>max){
max=exi.get(points[i]);
}
}else{
double k=(double)(points[i].y-points[j].y)/(points[i].x-points[j].x);
if(map.get(k)==null){
if(exi.get(points[i])!=null){
map.put(k,1+exi.get(points[i]));
}else{
map.put(k,2);
}
}else{
int v=map.get(k);
map.put(k,++v);
}
if(map.get(k)>max){
max=map.get(k);
}
}

}
}
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: