/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
// 1. consider same points
public int maxPoints(Point[] points) {
int maxCount = points.length == 0 ? 0: 1;
for(int i = 0; i<points.length; i++){
Map<Double, Integer> slopes = new HashMap<Double, Integer>();
int equalPoints = 0;
for( int j = 0; j < points.length; j++ ){
if(j == i){
continue;
}
if(points[i].x == points[j].x && points[i].y == points[j].y){
equalPoints++;
}else{
double k = ((double)(points[j].y - points[i].y))/(points[j].x - points[i].x);
if(slopes.containsKey(k)){
slopes.put(k, slopes.get(k)+1);
}else{
slopes.put(k,2);
}
}
if(maxCount < equalPoints + 1){
maxCount = equalPoints + 1;
}
}
for(Double slope: slopes.keySet()){
if(slopes.get(slope) + equalPoints > maxCount){
maxCount = slopes.get(slope) + equalPoints;
}
}
}
return maxCount;
}
}Leetcode习题:Max Points On a Line
最新推荐文章于 2023-03-12 15:35:06 发布
本文介绍了一种寻找平面上共线点的最大数量的算法。通过计算每两点间斜率并利用哈希表记录斜率出现次数,该算法能有效地找出具有相同斜率的点集合,即共线点。特别地,算法考虑了重复点的情况。
7万+

被折叠的 条评论
为什么被折叠?



