題目描述 Given n points on a 2D plane, find the maximum number of points that lie on the same straight

import java.util.*;
public class Solution {
    public int maxPoints(Point[] points) {
        if(points.length<2)
            return points.length;
        int flag=0;
        for(int i=0;i<points.length;i++){
           
            Map<Float,Integer> map=new HashMap<>();
            int dup=0,ver=0;//重複---垂直
            Point p=points[i];
            for(int j=0;j<points.length;j++){
                  if(i==j)
                      continue;
          
            if(points[j].x==p.x){
                if(points[j].y==p.y)
                    dup++;//重複1
                else   
                    ver++;//垂直1
                
            }else{
                float k=(float)(p.y-points[j].y)/(p.x-points[j].x);
                if(map.get(k)==null)
                    map.put(k,1);
                else{
                   int x=map.get(k)+1;
                    map.put(k,x);
                }
            }
            }
            int  tem=ver;
            for(float k:map.keySet()){
                tem=Math.max(tem,map.get(k));
            }
           flag=Math.max(flag,tem+dup+1);     
        }
        return flag;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章