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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章