您的位置:首页 > 其它

Leetcode-max-points-on-a-line

2016-07-09 22:34 405 查看


题目描述

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

题目越短,事情越大!

一个二维坐标系中有n个点,求出在同一条直线上的点的个数的最大值。

注意:在同一条线上,不规定横线或竖线,斜线也可以!

这就需要用到斜率了。我们运用暴力搜索,从第一个点开始,记为初始点,依次比较其余所有的点与该点的关系,首先计算相同点的个数,如果不相同的点,计算该点与初始点的斜率,存入HashMap中,key为斜率值,value为2,往后继续 计算斜率,判断HashMap中是否包含该斜率,如果包括,则该斜率对应的value值加1,否则,将该key加入到HashMap中。一层循环结束后,计算HashMap中最大的值,然后加上相同点个数。得出与当前初始点同一条线的个数总和最大值。外层循环结束以后,比较所有的最大值,得出最终的最大值,返回。

* class Point {
*     int x;
*     int y;
*     Point() { x = 0; y = 0; }
*     Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.*;
public class Solution {
public int maxPoints(Point[] points) {
int n = points.length;
if(n == 0 || points == null)
return 0;
if(n == 1)
return 1;

int max = 1;
for(int i=0; i<n; i++){
HashMap<Float, Integer> hm = new HashMap<Float, Integer>();
int same = 0;
int localmax = 1;
for(int j=0; j<n; j++){
if(i == j)
continue;
if(points[i].x == points[j].x && points[i].y == points[j].y){
same++;
continue;  //找到相同的,则跳过接下来的步骤,开始下一次循环
}
float slope =((float)(points[i].y-points[j].y)) / (points[i].x-points[j].x);
if(hm.containsKey(slope))
hm.put(slope, hm.get(slope)+1);
else
hm.put(slope, 2);
}
for(Integer value:hm.values())
localmax = Math.max(localmax, value);
localmax += same;
max = Math.max(max, localmax);
}
return max;
}
}


程序参考了:
http://www.cnblogs.com/springfor/p/3896120.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: