題目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
題目大意:
給出一組點,求在同一條直線上的點的最大數。
思路:
首先記錄下重合的點的數目,和斜率不存在時,處於同一條直線上的點的數目。之後使用HashMap數據結構來存儲和這個點各個斜率上點的個數。統計完成之後將斜率不存在時點的數目設爲最大值,以此和斜率存在時的點的數目進行比較。取出最大值(不包括和已知點重合的點的數目)。之後和之前求出的最大值進行一個比較,不要忘記在比較的時候需要在當前求出的最大值上加上重合點的數目。最後返回求出的最大值。
解題代碼:
import java.util.HashMap;
import java.util.Iterator;
public class Solution{
public int maxPoints(Point[] points) {
int result = 0;
int fresult = 0;
//數組長度小於2時的處理
if(points.length < 2){
return points.length;
}
//定義一個哈希表用於存儲斜率相同的點的個數
HashMap<Double, Integer>hash = new HashMap<Double,Integer>();
//重合的部分
int rep = 0;
//非重合的部分
int dif = 0;
//計算重合部分的數量
for(int i=0;i<points.length;i++){
hash.clear();
rep = 1;
dif = 0;
for(int j=0;j<points.length;j++){
if(points[i].x == points[j].x){
if(i == j){
continue;
}
if(points[i].y == points[j].y){
rep++;
}else{
dif++;
}
}else{
//收集各個斜率下的個數
double k = ((double)points[j].y - (double)points[i].y)/((double)points[j].x - (double)points[i].x);
if(!hash.containsKey(k)){
hash.put(k, 1);
}else{
hash.put(k, hash.get(k)+1);
}
}
}
result = dif;
//遍歷哈希表
Iterator<Double>ite = hash.keySet().iterator();
while(ite.hasNext()){
result = Math.max(result, hash.get(ite.next()));
}
fresult = Math.max(fresult, result+rep);
}
return fresult;
}
}