码迷,mamicode.com
首页 > 其他好文 > 详细

Max Points on a Line

时间:2015-04-23 15:31:07      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * 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 {
    public int maxPoints(Point[] points) {
        // ref http://www.cnblogs.com/springfor/p/3896120.html
        // ref http://blog.csdn.net/linhuanmars/article/details/21060933
        if(points==null || points.length==0) return 0;
        if(points.length==1) return 1;
        int max = 1;
        double slope = 0.0;
        for(int i=0;i<points.length-1;i++){
            int local = 1;
            HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
            int same = 0;             // points that are on the same position of i
            for(int j=i+1;j<points.length;j++){
                if(points[i].x ==points[j].x &&points[i].y ==points[j].y){
                    same++;
                    continue;
                }else if(points[i].y ==points[j].y){
                    slope  =0.0;
                }
                else if (points[i].x ==points[j].x){
                    slope  =(double) Integer.MAX_VALUE; 
                }
                else
                    slope = (double)(points[i].y - points[j].y)/(points[i].x - points[j].x); 
                if(hm.containsKey(slope)){
                    hm.put(slope,hm.get(slope)+1);
                }else{
                    hm.put(slope,2);
                }
            }
            for(Integer v: hm.values()){
                local = Math.max(local, v);
            }
            local += same;
            max = Math.max(max,local);
        }
        return max;
    }
}

 

Max Points on a Line

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4450375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!