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的差异。

  1. public int maxPoints(Point[] points) {
  2. int plen = points.length;
  3. if(plen == 0) {
  4. return 0;
  5. }
  6. int max_value = 0;
  7. Map<Double,Integer> scope = new HashMap<Double,Integer>();
  8. for(int i=0;i<plen;i++) {
  9. int dup = 1;
  10. scope.clear();
  11. scope.put(Double.MAX_VALUE,0);
  12. for(int j=i+1;j<plen;j++) {
  13. if(points[j].y==points[i].y && points[j].x == points[i].x) {
  14. dup++;
  15. continue;
  16. }
  17. if(points[j].x == points[i].x) {
  18. scope.put(Double.MAX_VALUE,scope.get(Double.MAX_VALUE) + 1);
  19. continue;
  20. }
  21. 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.
  22. if(k==-0.0) k=0.0;  //可以把-0.0 转换成0.0 或者直接计算时把int强转换为double
  23. if(scope.containsKey(k)) {
  24. scope.put(k,scope.get(k)+1);
  25. } else {
  26. scope.put(k,1);
  27. }
  28. }
  29. Iterator iter = scope.entrySet().iterator();
  30. while(iter.hasNext()) {
  31. Map.Entry entry = (Map.Entry)iter.next();
  32. Integer value = (Integer)entry.getValue();
  33. if(dup + value > max_value) {
  34. max_value = dup + value;
  35. }
  36. }
  37. }
  38. return max_value;
  39. }

C++代码:相对简洁一些

  1. int maxPoints(vector<Point> &points) {
  2. int psz=points.size();
  3. if(psz==0) return 0;
  4. map<double,int> mp;
  5. int maxpoint=0;
  6. for(int i=0;i<psz;i++) {
  7. mp.clear();
  8. mp[INT_MIN]=0;
  9. int dup=1;
  10. for(int j=i+1;j<psz;j++) {
  11. if(points[j].x==points[i].x && points[j].y==points[i].y) {
  12. dup++;
  13. } else if(points[j].x == points[i].x) {
  14. mp[INT_MAX]++;
  15. } else {
  16. double k=(points[j].y-points[i].y)*1.0/(points[j].x-points[i].x);
  17. mp[k]++;
  18. }
  19. }
  20. for(map<double,int>::iterator it=mp.begin();it!=mp.end();it++) {
  21. if(it->second + dup > maxpoint) maxpoint = it->second + dup;
  22. }
  23. }
  24. return maxpoint;
  25. }
posted @ 2014-07-28 20:46  purejade  阅读(93)  评论(0编辑  收藏  举报