码迷,mamicode.com
首页 > 其他好文 > 详细

Max Points on a Line

时间:2014-06-30 15:48:45      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   

题目

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

方法

每次选择一个点,和其他n - 1个点,进行判断,统计最多的。
	double computeSlope(Point a, Point b) {
		  
		  double slope;
		  if (a.x == b.x) {
			  return Double.MAX_VALUE;
		  } else {
			  double yDiff = (double)(a.y - b.y);
			  double xDiff = (double)(a.x - b.x);
			  slope = yDiff/xDiff;
			  return slope;
		  }
	}
    public int maxPoints(Point[] points) {
        if (points == null || points.length == 0) {
        	return 0;
        }
        int len = points.length;
        if (len <= 2) {
        	return len;
        }
        int max = 1;
        Map<Double, Integer> map = new HashMap<Double, Integer>();
        for (int i = 0; i < len; i++) {
        	map.clear();
        	int tempMax = 1;
        	int equal = 0;
        	for (int j = 0;j < len; j++) {
        		if (i != j) {
        		    if (points[i].x == points[j].x && points[i].y == points[j].y) {
        		        equal++;
        		    } else {
            		    double slope = computeSlope(points[i], points[j]);
            			if (!map.containsKey(slope)) {
            			    if (tempMax == 1) {
            			        tempMax = 2;
            			    }
            				map.put(slope, 1);
            			} else {
            				int temp = map.get(slope);
            				if (temp + 2 > tempMax) {
            					tempMax = temp + 2;
            				}
            				map.put(slope, temp + 1);
            			}
        		    }

        		}
        	}
        	if (max < tempMax + equal) {
        		max = tempMax + equal;
        	}
        }
        return max;
    }


Max Points on a Line,布布扣,bubuko.com

Max Points on a Line

标签:java   leetcode   

原文地址:http://blog.csdn.net/u010378705/article/details/35815077

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!