同一直線上最多的點的個數——Leetcode系列(三)

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

Clarification:

  • Count two if two points are at the same position.
My Answer:
/**
 * 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 result = 0;
        for(int i = 0; i < points.length; i++){
            Map<String,Integer> map = new HashMap<String,Integer>();
            int mx = 1;
            int same = 0;
            for(int j = i + 1; j < points.length; j++){
                double x = points[i].x - points[j].x;
                double y = points[i].y - points[j].y;
                if (x == 0 && y == 0){
                    same++;
                    continue;
                }
                String key = null;
                if (x == 0){
                    key = "V" + points[i].x;
                }else{
                    double k = y / x;
                    if (k == -0.0){
                        key = "" + 0;
                    }else{
                        key = "" + k;
                    }
                }
                if(map.containsKey(key)){
                    map.put(key,map.get(key)+1);
                }else{
                    map.put(key,2);
                }
                if(mx < map.get(key)){
                    mx = map.get(key);
                }
            }
            mx += same;
            if(result < mx){
                result = mx;
            }
        }
        return result;
    }
}

題目來源:https://oj.leetcode.com/problems/max-points-on-a-line/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章