标签:des style blog color strong for
Problem Description:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution:
1 public int maxPoints(Point[] points) { 2 if (points.length <= 1) { 3 return points.length; 4 } 5 Map<Double, Integer> map = new HashMap<Double, Integer>(); 6 int maxPoints = 0; 7 for (int i = 0; i < points.length; i++) { 8 map.clear(); 9 int samePointCount = 1; 10 int max = 0; 11 for (int j = i+1; j < points.length; j++) { 12 if (points[i].x == points[j].x && 13 points[i].y == points[j].y) { 14 samePointCount++; 15 } else { 16 double slope = Double.MAX_VALUE; 17 if (points[i].y == points[j].y) { 18 slope = 0; 19 } 20 else if (points[i].x != points[j].x) 21 slope = (points[i].y - points[j].y) / (double) (points[i].x - points[j].x); 22 if (! map.containsKey(slope)) { 23 map.put(slope, 1); 24 } else { 25 map.put(slope, map.get(slope)+1); 26 } 27 28 if (map.get(slope) > max) { 29 max = map.get(slope); 30 } 31 32 } 33 } 34 if (max + samePointCount > maxPoints) { 35 maxPoints = max + samePointCount ; 36 } 37 } 38 return maxPoints; 39 40 }
Problem Max Points On a Line,布布扣,bubuko.com
标签:des style blog color strong for
原文地址:http://www.cnblogs.com/liew/p/3815008.html