美文网首页
149 Max Points on a Line

149 Max Points on a Line

作者: 火焰婆婆 | 来源:发表于2015-09-12 16:41 被阅读0次

    149
    Max Points on a Line
    13.0%
    Hard
    不优化,直接数
    数个数用HashMap

    public class Solution {
        public int maxPoints(Point[] points) {
            if (points.length<=2) return points.length;
            int max = 2;
            for (int i=0;i<points.length;i++){
                int sameCount=1, infCount=0, zeroCount = 0, otherLineCount = 0;
                HashMap<Double, Integer> counter = new HashMap<Double, Integer>();
                for (int j=i+1;j<points.length;j++){
                    if (points[i].x==points[j].x && points[i].y==points[j].y) sameCount++;
                    else if (points[i].x == points[j].x) infCount++;
                    else if (points[i].y == points[j].y) zeroCount++;
                    else{
                        Double k = (double)(points[j].y - points[i].y) / (points[j].x - points[i].x);
                        if (!counter.containsKey(k)) counter.put(k,1);
                        else counter.put(k, counter.get(k)+1);
                        otherLineCount = Math.max(otherLineCount, counter.get(k));
                    }
                }
                max = Math.max(max, otherLineCount + sameCount);
                max = Math.max(max, infCount + sameCount);
                max = Math.max(max, zeroCount + sameCount);
            }
            return max;
        }
    }
    

    优化

    相关文章

      网友评论

          本文标题:149 Max Points on a Line

          本文链接:https://www.haomeiwen.com/subject/iuwpcttx.html