Failed, but why?


  • 0
    Y

    I think my code is 99% like the right one. Even though it is quiet efficient.

    Is there anything we need to pay attention to in terms of accurcy loss? I saw people do gcd instead of dividing? any specific reason?

    Thanks folks,

    static class Line
    {
    double a;
    double b;
    double c;
    Boolean isVertical;
    Boolean isHorizontal;
    int hash = -1;

    public Line(Point p1, Point p2)
    {
    
      if (p1.x == p2.x)
      {
        isVertical = true;
        c = p1.x;
      }
      else if (p1.y == p2.y)
      {
        isHorizontal = true;
        c = p1.y;
      }
      else
      {
        this.a = (double) (p1.y - p2.y) / ((double) (p1.x - p2.x));
        this.b = (p1.y + p2.y - a * p1.x - a * p2.x) / 2;
      }
    }
    
    @Override
    public int hashCode()
    {
      if (hash < 0)
      {
        String temp = a + "" + isVertical + "" + b + isHorizontal + c;
        this.hash = temp.hashCode();
      }
    
      return hash;
    }
    
    @Override
    public boolean equals(Object other)
    {
      return this == other ||
              (other != null && other instanceof Line && this.hashCode() == other.hashCode());
    }
    
    @Override
    public String toString()
    {
      return "a = " + a + " " + "b = " + b + " " +
              "c = " + c + " " + "isVertical " + isVertical + " " + "isHorizontal " + isHorizontal;
    }
    

    }

    public static int maxPoints(Point[] points)
    {
    Map<Line, Integer> lines = new HashMap<>();

    if(points == null) {
      return 0;
    }
    
    if (points.length <= 2) {
      return points.length;
    }
    
    int result = 0;
    
    for (int i = 0; i < points.length; i++) {
    
      int samePoint = 0;
      int max = 0;
    
      for (int j = i + 1; j < points.length; j++) {
        if(points[i].x == points[j].x && points[i].y == points[j].y) {
          samePoint++;
        } else {
    
          Line newLine = getNewLine(points[i], points[j]);
    
          if (lines.containsKey(newLine)) {
            int newVal = lines.get(newLine) + 1;
            lines.put(newLine, newVal);
            max = Math.max(newVal, max);
          } else {
            lines.put(newLine, 0);
            if (max == 0) {
              max++;
            }
          }
        }
    
      }
    
      result = Math.max(result, max + samePoint + 1);
    }
    
    return result;
    

    }


Log in to reply
 

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