您的位置:首页 > 其它

LintCode:最多有多少個點在一條直綫上

2017-04-23 13:32 190 查看
一.題目描述

给出二维平面上的n个点,求最多有多少点在同一条直线上。

二.思路和代碼

用哈希表存储斜率相同的点,遍历即可,只要特殊处理两个点相同和垂直于X轴(x坐标相同)的情况

public class Solution {
    /**
     * @param points an array of point
     * @return an integer
     */
    public int maxPoints(Point[] points) {
        // Write your code here

         if(points == null || points.length==0){
            return 0;
        }

        double vertical = Integer.MAX_VALUE;
        double same = Integer.MIN_VALUE;
        HashMap<Double,Integer> map= new HashMap<Double,Integer>();
        int result = 0;
        
        for(int  i = 0;i < points.length ; i++){
            map.clear();       
            map.put(same,1);  
            int max = 0;
            for(int j = i + 1 ; j < points.length ; j++){
                                
                double k = 0;

                if(points[j].x == points[i].x && points[j].y == points[i].y){
                    max++;
                    continue;
                }
                
                
                if(points[j].x - points[i].x== 0){
                    k = vertical;
                }else{
                    k = 0.0+(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x);
                }
                
                if(map.containsKey(k)){
                    map.put(k,map.get(k)+1);
                }else{
                    map.put(k, 2);
                }
            }
            
            for(int temp:map.values()){
                if(temp+max>result){
                    result=temp+max;
                }
            }
        }
        
        return result;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: