骰子求和

https://www.cnblogs.com/bozhou/p/6971081.html

题目:给出二维平面上的n个点,求最多有多少点在同一条直线上。

例子:给出4个点:(1, 2),(3, 6),(0, 0),(1, 3)。一条直线上的点最多有3个。

方法:取定一个点points[i],遍历其他所有节点,然后统计斜率相同的点数(用map(float, int)记录斜率及其对应点数,取map中点数最多的斜率),并求取最大值即可。

class Solution {

public:

int maxPoints(vector &points) {

// IMPORTANT: Please reset any member data you declared, as

// the same Solution instance will be reused for each test case.

unordered_map mp;

int maxNum = 0;

for(int i = 0; i < points.size(); i++)

{

mp.clear();

mp[INT_MIN] = 0;

int duplicate = 1;

for(int j = 0; j < points.size(); j++)

{

if(j == i) continue;

if(points[i].x == points[j].x && points[i].y == points[j].y)

{

duplicate++;

continue;

}

float k = points[i].x == points[j].x ? INT_MAX : (float)(points[j].y - points[i].y)/(points[j].x - points[i].x);

mp[k]++;

}

unordered_map::iterator it = mp.begin();

for(; it != mp.end(); it++)

if(it->second + duplicate > maxNum)

maxNum = it->second + duplicate;

}

return maxNum;

}

};

你可能感兴趣的:(骰子求和)