Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 149. Max Points on a Line

Rain Hu

149. Max Points on a Line


一、題目

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

Example 1:
plane1

Example 2: plane2

Constraints:


二、分析

三、解題

1.

int maxPoints(vector<vector<int>>& points) {
    int n = points.size();
    int res = 0;
    for (int i = 0; i < n; i++) {
        int& x0 = points[i][0];
        int& y0 = points[i][1];
        unordered_map<double,int> map;
        for (int j = 0; j < n; j++) {
            if (i == j) continue;                   // 若等於自己則跳過
            int& x1 = points[j][0];
            int& y1 = points[j][1];
            if (x0 == x1) {                         // 當分母為 0 時特別處理
                int& cnt = ++map[INT_MAX];
                res = max(res, cnt);
            } else {
                double m = (y1-y0)/(1.0*(x1-x0));   // 注意將斜率轉成 double
                int& cnt = ++map[m];
                res = max(res, cnt);
            }
        }
    }
    return res + 1;                                 // 答案記得加 1,加上自己
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 100. Same Tree
Next
[LeetCode] 452. Minimum Number of Arrows to Burst Balloons