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

【Leetcode】Max Points on a Line

时间:2016-06-12 02:41:43      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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.


思路:

对所有可以配对的点计算他们之间的斜率,并保存。时间复杂度O(n^2),空间复杂度为O(n)。


算法:

 	public int maxPoints(Point[] points) {
		if (points.length == 0) {
			return 0;
		} else if (points.length == 1) {
			return 1;
		}

		int max = 1;
	
		for (int i = 0; i < points.length; i++) {
			HashMap<Double, Integer> counts = new HashMap<Double, Integer>();// 斜率和该斜率的点的个数
			int x2 = points[i].x, y2 = points[i].y;
			int samePoint = 0;
			int localMax = 1;
			
			for (int j = 0; j < i; j++) {
				int x1 = points[j].x, y1 = points[j].y;
				if (x1 == x2 && y1 == y2) {
					samePoint++;
					continue;
				}
				double a = 0;//斜率
				if (x2 == x1) {
					a = Integer.MAX_VALUE;
				} else {
					a = (double)(y2 - y1) / (double)(x2 - x1); //要将点坐标int强转成double表示斜率
				}
				if (counts.containsKey(a)) {
					counts.put(a, counts.get(a) + 1);
				} else {
					counts.put(a, 2);
				}
			}

			for(Integer n:counts.values()){//遍历跟前面点最多直线的个数
				localMax = Math.max(localMax,n);
			}
			max = Math.max(max, localMax+samePoint);
		}
		return max;
	}


【Leetcode】Max Points on a Line

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51615494

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