LeetCode - Max Points on a Line

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.


 通过计算斜率来判断是否在一条直线上,要注意首尾点可能重复,另外java double类型的 0 和 -0是不一样的,最后O(n平方)过了,O(2n平方)超时了,

public class Solution {
    public int maxPoints(Point[] points) {
      int result = 0;
		
		HashMap<Double,Integer> v = new HashMap<Double,Integer>();
		for(int i = 0; i < points.length ; ++i){
			int total = 0;
			int special = 0;
			int multiple = 1;
			for(int j = i+1 ; j < points.length ; ++j){
				if(points[j].x != points[i].x ){
					double ratio = (double)(points[j].y - points[i].y)/(double)(points[j].x - points[i].x);
					if((Math.abs(ratio) - 0) < 0.0000001){
						ratio = 0d;
					}
					v.put(ratio,v.get(ratio) == null?1:v.get(ratio)+1);
					int size = v.get(ratio);
					if(total < size ){
						total = size;
					}
				}else if(points[j].x == points[i].x && points[j].y != points[i].y){
					special ++;
				}else{
					multiple ++;
				}
			}
			v.clear();
			if(result < special + multiple){
				result = special + multiple;
			}
			if(result < total + multiple){
				result = total + multiple;
			}
		}
		return result;
    }
}

Submission Result: Accepted


发布了24 篇原创文章 · 获赞 10 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章