[leetCode]:Max Points on a Line

语言 :JAVA

思路 :1、多点能组成一条直线,则必有基于某起始点,其他点相应的斜率相等。

              2、为了避免计算斜率出现的精度问题,采用最大公约数,若a/b = c/d,则必有a/b = e*g/f*g,如此当算出c、d的公约数g后,即可简化右侧等式。所有在一条直线上的    点都会具有相同的e,f值。以e,f为键,值则存储在这条线上的点的数量。

              3、注意到例如e,g为(1,-2),(-1,2)是两条不同的线,因此为了加以区别,在gcd()中,保留x轴的数值符号。

代码:

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    
    int gcd(int a, int b) {
		return a==0 ? b : a/Math.abs(a) * Math.abs(gcd(b%a, a)); 
	}
	
    public int maxPoints(Point[] points) {
    	int result = 0;
    	for (int i=0; i<points.length; i++) {
    		HashMap<String, Integer> count = new HashMap<String, Integer>();
    		int same = 1;
    		int mx = 0;
    		int newValue;
    		for (int j=i+1; j<points.length; j++) {
    			int x = points[i].x - points[j].x;
    			int y = points[i].y - points[j].y;
    			int g = gcd(x, y);
    			if (g == 0) {
    				same++;
    				continue;
    			}
    			x /= g;
    			y /= g;
    			String keyString = x + " " + y;
    			if (count.containsKey(keyString)) {
    			    newValue = count.get(keyString) + 1;
    			} else {
    				newValue = 1;
    			}
    			count.put(keyString, newValue);
    			mx = Math.max(mx, newValue);
    		}
    		result = Math.max(result, mx+same);
    	}
        return result;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值