Leetcode: 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.

 

解決:

import java.util.HashMap;
import java.util.Map;

class Point {
	int x;
	int y;

	Point() {
		x = 0;
		y = 0;
	}

	Point(int a, int b) {
		x = a;
		y = b;
	}
}
/**
 * 暴力破解:
 * 遍歷所有的點,每次取一個點,計算這個點與其他點斜率k,對k統計,找最大的。
 * 注意相同的點, 水平或豎直同線的點。
 * @author Administrator
 *
 */
public class LinePoints {
	public int maxPoints(Point[] points) {
		if (points.length < 2)
			return points.length;

		int global_max = 0;

		Map<Double, Integer> map_k = new HashMap<Double, Integer>();

		for (int i = 0; i < points.length; i++) {//遍歷,每次取一點A
			int one_point_max = 0;
			int h_max = 0;
			int same_point_num = 0;
			map_k.clear();

			for (int j = 0; j < points.length; j++) {//計算點A與其他點的斜率k
				if (i == j) {// itself
					continue;
				} else {
					if (points[i].x == points[j].x
							&& points[i].y == points[j].y) {// same point
						same_point_num++;
						continue;
					} else {
						if (points[i].x == points[j].x) {// 豎直同線的點
							h_max++;
							if (h_max > one_point_max)
								one_point_max = h_max;
						} else {
							double k = 0;
							if (points[i].y == points[j].y)//水平同線的點
								k = 0;
							else
								k = ((double) (points[i].y - points[j].y))
										/ ((double) (points[i].x - points[j].x));

							int k_v = 1;
							Double dk = new Double(k);
							if (map_k.get(dk) != null) {
								k_v = map_k.get(dk) + 1;
							}
							map_k.put(dk, new Integer(k_v));
							if (k_v > one_point_max)
								one_point_max = k_v;
						}
					}

				}

			}// end of for
			if (one_point_max + same_point_num > global_max)
				global_max = one_point_max + same_point_num;

		}// end of for

		return global_max + 1;
	}

	public static void main(String[] args) {
		LinePoints lp = new LinePoints();
		Point[] points = new Point[2];
		points[0] = new Point(0, 0);
		points[1] = new Point(0, 0);

		int s = lp.maxPoints(points);
		System.out.println(s);
	}
}

 

參考:

http://blog.csdn.net/worldwindjp/article/details/18882849

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章