Given n points
on a 2D plane, find the maximum number of points that lie on the same straight line.
给出n个点,判断在这些点中在同一直线最多的点,有几个?
1 首先想到这的确可以用暴力破解来做。两点确定一条直线,那么每次找两个点,然后算其他点再这条直线上有几个,记录;最后最多的数量就是答案。可是这需要O(n^3)的时间复杂度,所以直接放弃代码,重新思考;
public class Solution { public int maxPoints(Point[] points) { if(points.length==0){ return 0; } if(points.length==1){ return 1; } int n = points.length; int sum =2; Map<Double,Integer> record = new HashMap<Double,Integer>(); for(int i =0;i<n;i++){ record.clear(); int duplicate =1; record.put(Double.MIN_VALUE,0); for(int j=0;j<n;j++){ if(i==j){ continue; } if(points[i].x==points[j].x&&points[i].y==points[j].y){ duplicate++; continue; } double k; if(points[i].x==points[j].x){ k = Integer.MAX_VALUE; } else{ k=(double)(points[j].y-points[i].y)/(points[j].x-points[i].x); } if(record.containsKey(k)){ record.put(k, record.get(k)+1); } else{ record.put(k, 1); } } for(Iterator<Integer> a = record.values().iterator(); a.hasNext();){ int temp = a.next(); if(temp+duplicate>sum){ sum = temp+duplicate; } } } return sum; } }