Simplest 24 line Java solution, no GCD only intuitive ratios


  • 1
    C
    public int maxPoints(Point[] points) {
            if(points == null || points.length == 0) return 0;
            int max = 0;
            for(int i=0;i<points.length-1;i++){
                HashMap<Double, Integer> pointsOnLine = new HashMap<>();
                int samePoint = 0, localMax = 0;
                for(int j=i+1;j<points.length;j++){
                    int x = points[j].x - points[i].x;
                    int y = points[j].y - points[i].y;
                    if(x == 0 && y== 0) {
                        samePoint++;
                        continue;
                    }
                    double ratio = findRatio(x,y);
                    if(!pointsOnLine.containsKey(ratio))
                        pointsOnLine.put(ratio, 1);
                    else pointsOnLine.put(ratio, pointsOnLine.get(ratio)+1);
                    localMax = Math.max(localMax, pointsOnLine.get(ratio));
                }
                max = Math.max(max, localMax + samePoint);
            }
            return max+1;
        }
        private Double findRatio(int x, int y){
            if(y == 0) return Double.MAX_VALUE;
            else return (double)x/(double) y + 0.0;
        }
    

  • 1
    T

    @cgxy1995 said in Simplest 24 line Java solution, no GCD only intuitive ratios:

    (double)x/(double) y + 0.0;

    Here, why do you use 'x/y' to get ratio instead of 'y/x' ?
    When I use 'y/x' to calculate the slope, I can't pass the test case of "[[0,0],[94911151,94911150],[94911152,94911151]]".
    Thank you.


  • 1
    S

    your code is the only working code in the entire message board that pass all the test cases. However, I think the line X/Y doesn't make sense and very likely will break new test cases, because you haven't really solve the problem which not to use double as the key. All the test cases are designed to break the code Y/X which is the slope of the line.


Log in to reply
 

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