1. 程式人生 > >LeetCode刷題筆記(窮舉):max-points-on-a-line

LeetCode刷題筆記(窮舉):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.

給定2D平面上的n個點,找出位於同一直線上的最大點數。

解題思路

兩點確定一條直線,同時,對於斜率不為零的直線,都有y=kx+b。對於重複點,肯定也算是共線,所以,我們首先計算重複點的個數,然後計算斜率為0時共線的點個數,最後再計算其他斜率下共線的點的個數。

需要兩重迴圈,第一重迴圈遍歷起始點a,第二重迴圈遍歷剩餘點b。

  • 如果a和b重合,duplicate累加;
  • 如果a和b不重合,且兩者斜率為0,則numVertical累加;
  • 如果a和b不重合,且兩者斜率不為零,則計算斜率並計入map中,同時更新map中對應值;
  • 內迴圈結束後,返回max(local + duplicate, numVertical + duplicate)與之前的最大值res的最大值,local和numVertical算是不同斜率下的最大值;
  • 外迴圈結束後,返回res。

C++版程式碼實現

/**
 * Definition for a point.
 * struct Point {
 *     int x;
 *     int y;
 *     Point() : x(0), y(0) {}
 *     Point(int a, int b) : x(a), y(b) {}
 * };
 */
class Solution { public: int maxPoints(vector<Point>& points) { if(points.size() <= 2) return points.size(); int res = 0; for(int i = 0; i < points.size() - 1; ++i){ unordered_map<double, int> map; int numVertical = 0
, local = 1, duplicate = 0; for(int j = i + 1; j < points.size(); ++j) if(points[i].x == points[j].x) if(points[i].y == points[j].y) //重複點 duplicate++; else //垂直點 numVertical == 0 ? numVertical = 2 : numVertical++; else { double slope = (points[i].y - points[j].y) * 1.0 / (points[i].x - points[j].x); map[slope] == 0 ? map[slope] = 2 : map[slope]++; local = max(local, map[slope]); } local = max(local + duplicate, numVertical + duplicate); res = max(res, local); } return res; } };

系列教程持續釋出中,歡迎訂閱、關注、收藏、評論、點贊哦~~( ̄▽ ̄~)~

完的汪(∪。∪)。。。zzz