Leetcode: Max Points on a Line .

10 篇文章 0 订阅

题目:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值