您的位置:首页 > 其它

LeetCode Max Points on a Line

2015-11-09 12:37 405 查看
原题链接在这里:https://leetcode.com/problems/max-points-on-a-line/

这道题就是给你一个2D平面,然后给你的数据结构是由横纵坐标表示的点,然后看哪条直线上的点最多。

(1)两点确定一条直线

(2)斜率相同的点落在一条直线上

(3)坐标相同的两个不同的点 算作2个点

利用HashMap,Key值存斜率,Value存此斜率下的点的个数。如果遇到重合的点,same来记录相同点的个数。

维护一个localmax,计算当前情况下的最大值;再维护一个全局Max来计算总的最大值。返回全局Max即可。

Time Complexity is O(n^2). Space is O(n). n是点的个数。

Note: localMax要初始化成1, 最小值就是1, 而不能是0.

一条竖线上的点如[3,4], [3,5]他们的斜率是Infinity. HashMap 的 key 就是infinity.

AC Java:

/**
* 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;
if(points.length == 1){
return max;
}
for(int i = 0; i<points.length; i++){

HashMap<Float,Integer> hm = new HashMap<Float,Integer>();//key存斜率,value存该斜率上的点
int same = 0; //重合的点的个数
int localMax = 1;  //error
for(int j = 0; j<points.length; j++){
if(i == j){
continue;
}else if(points[i].x == points[j].x && points[i].y == points[j].y){
same++;
continue;
}
float slope = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
if(!hm.containsKey(slope)){
hm.put(slope,2);
}else{
hm.put(slope,hm.get(slope)+1);
}
}
for(int count : hm.values()){
localMax = Math.max(localMax,count);
}
localMax +=same;
max = Math.max(max,localMax);
}
return max;
}
}


Reference: /article/4896946.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: