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.


分析:

题目是给定一个二维平面上的点,希望求得这个平面上经过最多点的直线经过了多少个点。解这个题目需要用到穷举的思想,即计算每个点到其他点的斜

率,如果斜率相同,则共线。按照这个思路我们可以创建一个键为double,值为int类型的HashMap,穷举每两个点之间的斜率时,判断HashMap中是否

存在该斜率,没有就创建这个斜率的键值对,有就将值加1。需要考虑与该点重合还有垂直的情况。


具体代码如下:


/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */

import java.util.HashMap;
public class Solution {
    public int maxPoints(Point[] points) {
    	int len = points.length;
        
        if (len < 2)
            return len;
        
        
        
        
        
        int ret = 0;
        for (int i = 0; i < len; i++){
            int chuizhi = 0;
        	int chonghe = 1;
            HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
            for (int j = 0; j < len; j++){
                if (i == j)
                    continue;
                else{
                    int diffX = points[i].x - points[j].x;
                    int diffY = points[i].y - points[j].y;
                    
                    if (diffX == 0 && diffY == 0){
                        chonghe++;
                    }
                    else if (diffX == 0){
                        chuizhi++;
                    }
                    else{
                        double slope = diffY*1.0/diffX;
                        if (hm.get(slope) == null){
                            hm.put(slope, 1);
                        }
                        else{
                            hm.put(slope, hm.get(slope)+1);
                        }
                        
                    }
                }
                
            }
            
            int max = chuizhi;
            for(double k : hm.keySet()){
                max = Math.max(max, hm.get(k));
            }
            
            ret = Math.max(ret, max+chonghe);
        }
        
        return ret;
    }
    
    
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值