题目描述
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
给定二维平面上的n个点,请你找出位于一条直线上的点的最大个数。
题目解析
暴力求解:
使用两层循环,注意第二层循环里面考虑相同的点,使用变量same来进行保存。在第二层循环中每次遍历完,需要在退出的时候,求出与该点在同一直线上的最大点的个数。
使用HashMap来保存斜率及其对应的点的个数,注意求斜率的时候,需要进行类型转换,需要先将分子或者分母的值进行强制类型转换为float。
代码如下:
/**
* 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.HashMap;
public class Solution {
public int maxPoints(Point[] points) {
if (points == null)
return 0;
if(points.length <= 2)
return points.length;
int max = 1;
for (int j = 0; j < points.length; j++)
{
HashMap<Float, Integer> map = new HashMap<Float, Integer>();
int same = 0;
int localMax = 1;
for (int i = 0; i < points.length; i++)
{
if(i == j)
continue;
if((points[i].x == points[j].x) && (points[i].y == points[j].y))
{
same++;
continue;
}
float scope = ((float)(points[i].y - points[j].y)/(points[i].x - points[j].x));
if(map.containsKey(scope))
{
map.put(scope, map.get(scope)+1);
}else
map.put(scope,2);
}
for(Integer value:map.values())
{
localMax = Math.max(localMax,value);
}
localMax += same;
max = Math.max(localMax,max);
}
return max;
}
}
代码中的一些HashMap的用法:
Map的遍历大体有3种:
1、遍历Map.entrySet():它的每一个元素都是Map.Entry对象,这个对象中,
放着的就是Map中的某一对key-value;
2、遍历Map.keySet():它是Map中key值的集合,我们可以通过遍历这个集合来
读取Map中的元素;
3、遍历Map.values():它是Map中value的集合,我们可以直接通过这个集合遍历
Map中的值,却不能读取key。
Map中元素存放是无序的
HashMap注意事项:
1,HashMap底层维护一个数组,我们向HashMap中所放置的对象实际上是存储在该数组当中;
2,当向HashMap中put一对键值时,它会根据key的hashCode值计算出一个位置,该位置就是此对象准备往数组中存放的位置。