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.
思想:以一个点为起点,计算以该点为起点的所有不同斜率上点的数目,从中挑选最大值。
java 代码: 注意java中int与int操作不会自动转换成double,如果结果为double,最好先转换成double。否则可能出现0.0 和 -0.0的差异。
- public int maxPoints(Point[] points) {
- int plen = points.length;
- if(plen == 0) {
- return 0;
- }
- int max_value = 0;
- Map<Double,Integer> scope = new HashMap<Double,Integer>();
- for(int i=0;i<plen;i++) {
- int dup = 1;
- scope.clear();
- scope.put(Double.MAX_VALUE,0);
- for(int j=i+1;j<plen;j++) {
- if(points[j].y==points[i].y && points[j].x == points[i].x) {
- dup++;
- continue;
- }
- if(points[j].x == points[i].x) {
- scope.put(Double.MAX_VALUE,scope.get(Double.MAX_VALUE) + 1);
- continue;
- }
- double k = (points[j].y - points[i].y)*1.0/(points[j].x-points[i].x); //[2,3],[3,3],[-5,5] 会得到0.0和-0.0.
- if(k==-0.0) k=0.0; //可以把-0.0 转换成0.0 或者直接计算时把int强转换为double
- if(scope.containsKey(k)) {
- scope.put(k,scope.get(k)+1);
- } else {
- scope.put(k,1);
- }
- }
- Iterator iter = scope.entrySet().iterator();
- while(iter.hasNext()) {
- Map.Entry entry = (Map.Entry)iter.next();
- Integer value = (Integer)entry.getValue();
- if(dup + value > max_value) {
- max_value = dup + value;
- }
- }
- }
- return max_value;
- }
C++代码:相对简洁一些
- int maxPoints(vector<Point> &points) {
- int psz=points.size();
- if(psz==0) return 0;
- map<double,int> mp;
- int maxpoint=0;
- for(int i=0;i<psz;i++) {
- mp.clear();
- mp[INT_MIN]=0;
- int dup=1;
- for(int j=i+1;j<psz;j++) {
- if(points[j].x==points[i].x && points[j].y==points[i].y) {
- dup++;
- } else if(points[j].x == points[i].x) {
- mp[INT_MAX]++;
- } else {
- double k=(points[j].y-points[i].y)*1.0/(points[j].x-points[i].x);
- mp[k]++;
- }
- }
- for(map<double,int>::iterator it=mp.begin();it!=mp.end();it++) {
- if(it->second + dup > maxpoint) maxpoint = it->second + dup;
- }
- }
- return maxpoint;
- }