题目:149. 直线上最多的点数 - 力扣(LeetCode)
水题。之前棋盘类的题做多了,一开始只想到了横竖斜四个方向,错了一次才想明白斜率是任意的。
class Solution {
public:int maxPoints(vector<vector<int>>& points) {if (points.size() == 1) {return 1;}size_t n = points.size();int ret = 1;int temp, x1, x2, y1, y2;for (int i = 0; i < n; i++) {for (int j = i + 1; j < n; j++) {auto& a = points[i];auto& b = points[j];temp = 2;if (a[0] == b[0]) {for (int k = 0; k < n; k++) {if (k == i || k == j) continue;if (points[k][0] == a[0]) {temp++;}}} else if (a[1] == b[1]) {for (int k = 0; k < n; k++) {if (k == i || k == j) continue;if (points[k][1] == a[1]) {temp++;}}} else {x1 = a[0] - b[0];y1 = a[1] - b[1];for (int k = 0; k < n; k++) {if (k == i || k == j) continue;x2 = a[0] - points[k][0];y2 = a[1] - points[k][1];if (x1 * y2 == x2 * y1) {temp++;}}}if (temp > ret) {ret = temp;}}}return ret;}
};