题干:Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Constraints:
- 1 <= points.length <= 300
- points[i].length == 2
- -104 <= xi, yi <= 104
- All the points are unique.
比较基础的一道hard题。首先考虑如何在二维坐标系确定一条无向直线,有两种思路:1、两点之间确定一条直线;2、点坐标+斜率。由两点组合确定的话数量会随点的个数上升而急剧增加且需要去重。这边考虑点坐标+斜率的方式确定直线。
由hashMap存储斜率+直线上点的个数,需要注意斜率需用double类型存储及边界条件:斜率为无穷大、double的0.0和-0.0。代码如下,供参考。
public static int maxPoints(int[][] points){ int length = points.length; if (length==1) return 1; int maxpoints=-1; for (int i=0;i<length-1;++i){ if (length-i<=maxpoints) break; Map<Double,Integer> line = new HashMap<>(); int x0 = points[i][0]; int y0 = points[i][1]; for (int j=i+1;j<length;++j){ int dx=points[j][0]-x0; int dy=points[j][1]-y0; double slope=Double.MAX_VALUE; if (dx!=0) slope=(double)dy/(double)dx; if (dy==0) slope=0; line.put(slope,line.getOrDefault(slope,1)+1); maxpoints=Math.max(maxpoints,line.get(slope)); } } return maxpoints; }
在这个思路下理解这道题其实难度够不上hard,但这个解法的时间空间复杂度都比较一般。
发散思维的话,有考虑过1、通过位图还原二维坐标图再BFS,2、DFS+剪枝的方法去解,但这两种在程序设计的难度上更大,欢迎有其他更优解法的朋友交流。