share my accepted java solution(modified original method which is not accepted right now)


  • 0
    T
    /**
     * Definition for a point.
     * class Point {
     *     int x;
     *     int y;
     *     Point() { x = 0; y = 0; }
     *     Point(int a, int b) { x = a; y = b; }
     * }
     */
    class Solution {
        public int maxPoints(Point[] points) {
            int max = 0;
            if(points==null || points.length<1){
                return 0;
            }
            for(int i=0;i<points.length;i++){
                Map<String,Integer> map = new HashMap<>();
                int samex = 1;
                int samep = 0;
                Point base = points[i];
                for(int j=0;j<points.length;j++){
                    if(j==i){
                        continue;
                    }       
                    Point cur = points[j];
                    if(cur.x==base.x&&cur.y==base.y){
                        samep++;
                    }
                    if(cur.x==base.x){
                        samex++;
                    }
                    
                    if(cur.x!=base.x){
                        String key = gcdStr(cur.y-base.y,cur.x-base.x);
                        if(map.containsKey(key)){
                            map.put(key,map.get(key)+1);
                        }else{
                            map.put(key,2);
                        }
                    }
                }
                
                int curMax = Math.max(samex,samep);
                for(String key:map.keySet()){
                    curMax = Math.max(curMax,map.get(key)+samep);
                }
                max = Math.max(max,curMax);
            }
            
            return max;
        }
        
        public String gcdStr(int x,int y){
            
            if(x==0){
                return 0+"";
            }
            int m=x;
            int n=y;
            while(m%n!=0){
                int d = m%n;
                m = n;
                n = d;
            }
            
            x/=n;
            y/=n;
            if(x<0&&y<0){
                return (-x)+"/"+(-y);
            }else if(x>0&&y>0){
                return x+"/"+y;
            }else if((x<0&&y>0) || (x>0&&y<0)){
                return "-"+Math.abs(x)+"/"+Math.abs(y);
            }
            
            return "";
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.