题目:
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);
- }
- }
参考: