Max Points on a Line

2014-11-24 11:05:13 · 作者: · 浏览: 0

题目原型:

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

基本思路:

题目的意思就是找到一条直线,让最多的点在这条直线上,那么利用数学中的斜率定义,如果两个点与另外一个的斜率相等,那么这两个点与另外一个点在同一条直线上。

下面用到求最大公约数,注意:一个正数和一个负数求最大公约数是没意义的。

	//通过斜率相等来求
	public int maxPoints(Point[] points)
	{
		int maxSum = 0;
		if(points==null||points.length==0)
			return 0;
		//如果只有一个点时
		if(points.length==1)
			return 1;
		//以一个点为基点,分别求出其余点与这个点之间斜率
		for(int i = 0;i
  
    map = new HashMap
   
    (); int maxSumtmp = 0; for(int j = 0;j
    
     map.get(str) maxSumtmp:map.get(str); } maxSum = Math.max(maxSumtmp+1+samePoint, maxSum); } return maxSum; } //最大公约数,如果最大公约数为0 ,说明这两个数为均为0 public int gcd(int a , int b) { return a==0 b:gcd(b%a, a); }