博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Max Points on a Line
阅读量:6579 次
发布时间:2019-06-24

本文共 2204 字,大约阅读时间需要 7 分钟。

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

【thought】Use two layers of loop to solve it.Do not start the second loop from points.begin() but item1+1 (item1 is the current item of the first loop).We can avoid accessing any 2 duplicated points which could compose one straight line with this method.Any better solution?If any there,pls tell me.Thanks.

1 #include 
2 #include
3 #include
4 #include
5 #include
6 7 using namespace std; 8 9 /**10 * Definition for a point.11 * struct Point {12 * int x;13 * int y;14 * Point() : x(0), y(0) {}15 * Point(int a, int b) : x(a), y(b) {}16 * };17 */18 19 bool typeisless(const Point &data1,const Point &data2){20 return data1.x < data2.x;21 }22 23 class Solution {24 public:25 26 int maxPoints(vector
&points) {27 if(points.size()==0) return 0;28 29 int last_x = (points.begin()->x) - 1;30 int maxnum = INT_MIN,curnum = 0;31 std::sort(points.begin(),points.end(),typeisless);32 for(vector
::iterator iter = points.begin();33 iter != points.end();++iter){34 if(iter->x == last_x){35 ++curnum;36 }else{37 last_x = iter->x;38 curnum = 1;39 }40 41 maxnum = maxnum
count_map;45 count_map.insert(pair
(0.0,0));46 47 for(vector
::iterator iter1 = points.begin();48 iter1 != points.end();++iter1){49 count_map.clear();50 int samepointnum = 0;51 52 for(vector
::iterator iter2 = iter1 + 1;53 iter2 != points.end();++iter2){54 55 if(iter2->x == iter1->x && iter2->y == iter1->y){56 ++samepointnum;continue;57 }else if(iter2->x == iter1->x)58 continue;59 else{60 double dslope = (static_cast
(iter2->y - iter1->y))/61 (static_cast
(iter2->x - iter1->x));62 if(count_map.find(dslope) != count_map.end()) ++count_map[dslope];63 else{64 count_map[dslope] = 1;65 ++count_map[dslope];66 }67 }68 }69 70 for(unordered_map
::iterator iter=count_map.begin();71 iter!=count_map.end();++iter){72 if(iter->second + samepointnum > maxnum){73 maxnum = iter->second + samepointnum;74 }75 }76 }77 78 return maxnum;79 }80 };

转载于:https://www.cnblogs.com/zhouyoulie/p/4009372.html

你可能感兴趣的文章
每日一记--cookie
查看>>
IOS 7 Study - UISegmentedControl
查看>>
八、通用类型系统
查看>>
JQuery的ajaxFileUpload的使用
查看>>
关于Integer类中parseInt()和valueOf()方法的区别以及int和String类性的转换.以及String类valueOf()方法...
查看>>
ios 控制器的生命周期
查看>>
JavaScript 特殊效果代码
查看>>
【?】codeforces721E Road to Home(DP+单调队列)
查看>>
MySQL 仅保留7天、一个月数据
查看>>
Diff Two Arrays
查看>>
下拉菜单
查看>>
[清华集训2014]玛里苟斯
查看>>
【MVC+EasyUI实例】对数据网格的增删改查(上)
查看>>
Project Euler 345: Matrix Sum
查看>>
你可能不知道的技术细节:存储过程参数传递的影响
查看>>
[摘录]调动员工积极性的七个关键
查看>>
.htaccess 基础教程(四)Apache RewriteCond 规则参数
查看>>
Android控件之HorizontalScrollView 去掉滚动条
查看>>
UVM中的class--2
查看>>
ORACLE 存储过程异常捕获并抛出
查看>>