2014年5月6日星期二

Loop Solution - Max Points on a Line

The basic idea is to build a map which contains the double and count values. Below is a n square solution that loop through the pool quad times. Be noticed that the second loop should base on the outer one, which is j = i as in code. Secondly, the duplicates need to be collected as well, which is the coincident as a variable name below.


/**
 * 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) {
        int maxLine = 0;

        for (int i=0; i<(points.length-maxLine); i++) {
            int coincident = 0;
            Map<Double, Integer> pointCounts = new HashMap<Double, Integer>();
            for (int j=i+1; j<points.length; j++) {
                Double slope;
                if (points[i].x==points[j].x && points[i].y==points[j].y) {
                    coincident++;
                    continue;
                } else if (points[i].x == points[j].x) {
                    slope = Math.PI;
                } else if (points[i].y == points[j].y) {
                    slope = 0.0; // logically we don't need this, but in practice i find that we do
                } else {
                    slope = new Double((double)(points[i].y-points[j].y) / (double)(points[i].x-points[j].x));
                }

                if (pointCounts.containsKey(slope))
                    pointCounts.put(slope, pointCounts.get(slope)+1);
                else
                    pointCounts.put(slope, new Integer(1));
            }
            maxLine = Math.max(maxLine, 1+coincident+maxValue(pointCounts));
        }

        return maxLine;
    }

    private int maxValue(Map<Double, Integer> doubleIntMap) {
        int max = 0;
        Set<Double> keys = doubleIntMap.keySet();
        Iterator iter = keys.iterator();
        while (iter.hasNext())
            max = Math.max(max, doubleIntMap.get(iter.next()));
        return max;
    }

没有评论: