Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example
Given 4 points: (1,2)
, (3,6)
, (0,0)
, (1,3)
.
The maximum number is 3
.
/** * 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 { /** * @param points an array of point * @return an integer */ public int maxPoints(Point[] points) { // Write your code here if(points == null || points.length == 0) return 0; int result = 0; HashMap<Double, Integer> map = new HashMap<Double, Integer>(); for(int i = 0; i < points.length; i++){ int dup = 1; int ver = 0; for(int j = i + 1; j < points.length; j++){ if(points[i].x == points[j].x){ if(points[i].y == points[j].y) dup++; else ver++; } else{ double slope = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); if(map.containsKey(slope)) map.put(slope, map.get(slope) + 1); else map.put(slope, 1); } } int count = 0; for(Map.Entry<Double, Integer> entry: map.entrySet()){ if(entry.getValue() > count) count = entry.getValue(); } result = Math.max(result, count + dup); result = Math.max(result, ver + dup); map.clear(); } return result; } }
lintcode-medium-Max Points on a Line
原文:http://www.cnblogs.com/goblinengineer/p/5335633.html