[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.

Solution:

 1 /**
 2  * Definition for a point.
 3  * class Point {
 4  *     int x;
 5  *     int y;
 6  *     Point() { x = 0; y = 0; }
 7  *     Point(int a, int b) { x = a; y = b; }
 8  * }
 9  */
10 public class Solution {
11     public int maxPoints(Point[] points) {
12         
13         if(points.length==1)
14         return 1;
15         
16         HashMap<Double, Integer> hm=new HashMap<Double, Integer>();
17         int result=0;
18         
19         for(int i=0;i<points.length-1;++i){
20             int infinitePoint=0;
21             int samePoint=1;
22             for(int j=i+1;j<points.length;++j){
23                 if(points[i].x==points[j].x){
24                     if(points[i].y==points[j].y){
25                         samePoint++;
26                     }else{
27                         infinitePoint++;
28                     }
29                 }else{
30                     double k=(points[j].y==points[i].y)?0.0:(1.0*((points[j].y)-points[i].y))/((points[j].x)-points[i].x);
31                     if(hm.containsKey(k)){
32                         int count=hm.get(k);
33                         hm.put(k, count+1);
34                     }else{
35                         hm.put(k, 1);
36                     }
37                 }
38             }
39             for(Integer iter:hm.values()){
40                 if(iter+samePoint>result){
41                     result=iter+samePoint;
42                 }
43             }
44             result=Math.max(result, infinitePoint+samePoint);
45             hm.clear();
46         }
47         return result;
48     }
49 }

Note:

真是被自己蠢哭了啊,以前遇到过的问题,该犯的错还是犯了。。。囧

注意要在每次循环后把map给清掉。

原文地址:https://www.cnblogs.com/Phoebe815/p/4091198.html