Monday, October 19, 2015

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: HashMap
只要不同点之间的斜率(ratio)相同,说明它们在同一条直线上。Key是ratio,value存点的个数。
每一个点跟它后面的所有点比较,两层循环,maxLocal保存当前点的map中在一条线上的点的最大个数, max保存整体上一条线上点的最大个数。
Run time complexity is O(n ^ 2), space complexity is O(n).
/**
 * 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) {
        if (points == null || points.length == 0) {
            return 0;
        }
        
        int max = 1;
        double ratio = 0.0;
        for (int i = 0; i < points.length - 1; i++) {
            int maxLoc = 1;
            int numOfSam = 0;
            HashMap map = new HashMap();
            
            for (int j = i + 1; j < points.length; j++) {
                if (points[j].x == points[i].x && points[j].y == points[i].y) {  // 两点重合
                    numOfSam++;
                    continue;
                } else if (points[j].x == points[i].x) {  // 两点水平
                    ratio = (double) Integer.MAX_VALUE;
                } else if (points[j].y == points[i].y) {  // 两点垂直
                    ratio = 0.0;
                } else {
                    ratio = (double) (points[j].y - points[i].y) / (double) (points[j].x - points[i].x);
                }
                
                if (map.containsKey(ratio)) {
                    map.put(ratio, map.get(ratio) + 1);
                } else {
                    map.put(ratio, 2);
                }
            }
            
            for (Integer value : map.values()) {
                maxLoc = Math.max(maxLoc, value);
            }
            maxLoc += numOfSam;  // 将重合的点加上
            max = Math.max(max, maxLoc);
        }
        
        return max;
    }
}
Referencehttp://blog.csdn.net/linhuanmars/article/details/21060933

No comments:

Post a Comment