zoukankan      html  css  js  c++  java
  • 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.

    /**
     * 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) {
            HashMap<Double, Integer> slopeMap = new HashMap<Double, Integer>();
            Integer result = 0;
            if(points == null || points.length == 0) return result;
            for(int i = 0; i < points.length; i ++){
                slopeMap.clear();
                Integer sameValue = 0;
                for(int j = i; j < points.length; j ++){
                //need to start from i, or should return result + 1. since we don't count point i itself
                    if(points[i].x == points[j].x && points[i].y == points[j].y){
                        sameValue ++;
                    }else{
                        Double slope = slopeForTwoPoint(points[i], points[j]);
                        if(slopeMap.containsKey(slope)){
                            slopeMap.put(slope, slopeMap.get(slope) + 1);
                        }else{
                            slopeMap.put(slope, 1);
                        }
                    }
                }
                Iterator it = slopeMap.values().iterator();
                while(it.hasNext()){
                    Integer val = (Integer)it.next();
                    result = Math.max(val + sameValue, result);
                }
                
                //if all the points are same points
                result = Math.max(sameValue, result);
            }
            return result;
        }
        
        public Double slopeForTwoPoint(Point a, Point b){
        //hashmap can have null as key, so take use of this feature.
            if(a.x == b.x) return null;
        //a.y == b.y case
            else if(a.y == b.y) return (double)0;
            else return ((double)a.y - (double)b.y) / ((double)a.x - (double)b.x);
        }
    }
  • 相关阅读:
    (3.4)常用知识-char与varchar的选择
    (3.3)常用知识-索引使用、维护与填充因子
    (3.2)常用知识-字符串处理
    (3.1)常用知识-日期处理
    基于Sql Server 2008的分布式数据库的实践
    将expression转化为数据类型int时发生算术溢出错误
    webserver and application server
    web前端
    linkin
    jquery load
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3440827.html
Copyright © 2011-2022 走看看