一、要求:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
解析:①、先任取一个点,判断其他剩下的所有点是否在一条直线上,统计个数;②、如果该个数大于maximum,修改maximum,③、继续选取下一个点,重复①②,直到全部点遍历完。
二、代码:
根据题目要求和以上分析,我们可以得到代码如下:
</pre><pre name="code" class="java"><span style="font-size:14px;"></span>
<pre name="code" class="java"><pre name="code" class="java">
<pre name="code" class="java"><span style="font-size:14px;"></span>
<span style="font-size:14px;">/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
import java.util.*;
public class Solution {
public int maxPoints(Point[] points) {
if (points.length < 3) return points.length;
int max = 0;//用于返回的结果,即共线点的最大个数
Map<Double, Integer> map = new HashMap<Double, Integer>();//保存同一个斜率的点的个数
for (int i = 0; i < points.length; i++) {//以每一个点为固定点
map.clear();
int duplicate = 1;//记录跟固定点重合的个数
for(int j = 0 ; j < points.length; j++){//遍历其他点,求其与固定点之间的斜率
if (i == j) continue;//如果是自己,跳过
double slope = 0.0;//斜率
if (points[i].x == points[j].x && points[i].y == points[j].y) {//如果跟固定点重合
duplicate++;
continue;
} else if (points[i].x == points[j].x) {//如果跟固定点在同一条竖线上,斜率设为最大值
slope = Integer.MAX_VALUE;
} else {//计算该点与固定点的斜率
slope = 1.0 * (points[i].y - points[j].y) / (points[i].x - points[j].x);
}
map.put(slope, map.containsKey(slope) ? map.get(slope) + 1 : 1);
}
//更新最优解
if (map.keySet().size() == 0) {//如果map为空
max = duplicate > max ? duplicate : max;
} else {
for (double key : map.keySet()) {
max = Math.max((duplicate + map.get(key)), max);
}
}
}
return max;
}
} </span>
三、参考博客链接:
Map接口笔记:http://blog.csdn.net/e421083458/article/details/8542536
LeetCode:http://blog.csdn.net/ljiabin/article/details/38904757