Thursday, December 19, 2013

Leetcode: Max Points on a Line

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

The following is a O(n^2 lg n) algorithm because I use TreeMap instead of HashMap.

 If I use HashMap, then the run time is O(n^2). But I did not find a way doing better than O(n^2).

Another question is that to use HashMap in java I need to define my own equals() and hashcode() functions, which is quite annoying. Especially hashcode() function, any one have a idea how to produce a good hashcode() function for this?


/**
 * 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.*;

class Slope implements Comparable<Slope>{
  int x;
  int y;
  Slope(int a, int b){
      if(b<0){
          a *= -1;
          b *= -1;
      }
      x = a; y = b;
  }
  public int compareTo(Slope other){
      return this.x * other.y - this.y * other.x;
  }
}

public class Solution {
    int numPointsCentered(Point[] points, int id){
        Map<Slope, Integer> counts = new TreeMap<Slope, Integer>();
        int num_same_point = 0;
        int return_max = 1;
        for(int i = 0; i < points.length; i++){
            if (i==id) continue;
            if (points[i].x==points[id].x && points[i].y==points[id].y){
                num_same_point++;
                continue;
            }
            Slope slope = new Slope(points[i].x - points[id].x, points[i].y - points[id].y);
            if(counts.containsKey(slope)){
                counts.put(slope, counts.get(slope) + 1);
            }else{
                counts.put(slope, 2);
            }
            return_max = Math.max(return_max, counts.get(slope));
        }
        return return_max + num_same_point;
    }
   
    public int maxPoints(Point[] points) {
        int num_points = 0;
        for(int i = 0; i < points.length; i++){
            int new_center_points = numPointsCentered(points, i);
            num_points = Math.max(num_points, new_center_points);
        }
        return num_points;
    }
}

No comments:

Post a Comment

Manacher's Longest Palindromic Substring Algorithm

http://manacher-viz.s3-website-us-east-1.amazonaws.com/#/