首页 > 代码库 > leetcode 149. Max Points on a Line
leetcode 149. 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.
两层循环,将在同一直线上的点放入hash table,找到hash table中的最大值。
1 int maxPoints(vector<Point> &points) 2 { 3 int max_points = 0, duplicate = 0; 4 unordered_map<float, int> htable; 5 double slope = 0; 6 int n = points.size(); 7 if (n <= 1) 8 return n; 9 10 for (int i = 0; i < n; i++)11 {12 duplicate = 1;13 htable.clear();14 for (int j = i + 1; j < n; j++)15 {16 if ((points[i].x == points[j].x) && (points[i].y == points[j].y))17 { 18 duplicate++;19 continue;20 }21 22 slope = (points[i].x == points[j].x) ? INT_MAX : (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);23 htable[slope]++;24 }25 for (unordered_map<float, int>::iterator it = htable.begin(); it != htable.end(); it++)26 {27 if (max_points < it->second + duplicate)28 max_points = it->second + duplicate;29 }30 max_points = max(max_points, duplicate);31 }32 33 return max_points;34 }
leetcode 149. Max Points on a Line
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。