Sunday, January 11, 2015

LeetCode 149: 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.
/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    public int maxPoints(Point[] points) {
        // Calculate slope of every two points
        // Store slope as key of hashmap; value is the number of points.
        // Note: Vertical line doesn't have slope (We can define it as Double.MAX_VALUE)
        // Check the straight lines point by point
        int n = points.length;
  
        if (n <= 2)
            return n;
            
        Map<Double, Integer> map = new HashMap<>();
        
        int max = 0;  
        int dup; // Number of duplicate points
    
        for(int i = 0; i < n; i++)
        {
            map.clear();  
            dup = 1;
            
            for (int j = 0 ; j < n; j++)
            {  
                if (i == j)
                    continue;  
                 
                double slope = 0.0;  
                
                if (points[i].x==points[j].x && points[i].y==points[j].y)
                {
                    dup++;
                    continue;  
                }
                else if (points[i].x == points[j].x)
                    slope = Double.MAX_VALUE;
                else
                    slope = (double)(points[i].y-points[j].y) / (double)(points[i].x-points[j].x);
            
                if (!map.containsKey(slope))
                    map.put(slope, 1);
                else
                    map.put(slope, map.get(slope)+1);
            }
        
            if (map.keySet().size() == 0)
                max = dup;
                
            for (double key : map.keySet())
                max = Math.max(max, dup+map.get(key));
        }
    
        return max; 
    }
}

No comments:

Post a Comment