98 lines
3.3 KiB
Java
98 lines
3.3 KiB
Java
package com.hong.www;
|
|
|
|
import java.util.HashMap;
|
|
|
|
public class A149 {
|
|
public int maxPoints(int[][] points) {
|
|
int finalcount = 0;
|
|
|
|
for (int i = 0; i < points.length; i++) {
|
|
HashMap<Float, Integer> K = new HashMap<>();
|
|
for (int j = i+1 ; j < points.length; j++) {
|
|
float k;
|
|
if(points[i][0] - points[j][0]!=0){
|
|
if(points[i][1] - points[j][1]==0){
|
|
k = 0;
|
|
}else{
|
|
k = (float)(points[i][1] - points[j][1]) / (points[i][0] - points[j][0]);
|
|
}
|
|
}else{
|
|
k = Float.POSITIVE_INFINITY; // Use a special value for vertical lines
|
|
}
|
|
if (K.containsKey(k)) {
|
|
if (K.get(k) + 1 >= finalcount) {
|
|
finalcount = K.get(k) + 1;
|
|
}
|
|
K.put(k, K.get(k) + 1);
|
|
} else {
|
|
K.put(k, 1);
|
|
if(finalcount<1){
|
|
finalcount=1;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
/* HashMap<Float, HashMap<Float, Integer>> KB = new HashMap<>();
|
|
for (int i = 0; i < points.length; i++) {
|
|
for (int j = i ; j < points.length; j++) {
|
|
if (i != j) {
|
|
float k;
|
|
float b;
|
|
if((points[i][0] - points[j][0])!=0){
|
|
|
|
k = (points[i][1] - points[j][1]) / (points[i][0] - points[j][0]);
|
|
b = points[i][1] - k * points[i][0];
|
|
}else{
|
|
k=0;
|
|
b=0;
|
|
}
|
|
|
|
|
|
if (KB.containsKey(k)) {
|
|
if (KB.get(k).containsKey(b)) {
|
|
if (KB.get(k).get(b) + 1 >= finalcount) {
|
|
finalcount = KB.get(k).get(b) + 1;
|
|
}
|
|
KB.get(k).put(b, KB.get(k).get(b) + 1);
|
|
|
|
} else {
|
|
KB.get(k).put(b, 1);
|
|
}
|
|
} else {
|
|
HashMap<Float, Integer> temp = new HashMap<>();
|
|
temp.put(b, 1);
|
|
KB.put(k, temp);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
if(finalcount==0&&points.length==1){
|
|
finalcount=1;
|
|
}else if(finalcount==0){
|
|
finalcount=2;
|
|
}
|
|
int count = 2;
|
|
while (count<finalcount){
|
|
count++;
|
|
int tempcount = 0;
|
|
for(int c=1;c<count;c++){
|
|
tempcount+=c;
|
|
}
|
|
if(tempcount==finalcount){
|
|
finalcount=count;
|
|
}
|
|
} */
|
|
return finalcount+1;
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
A149 solution = new A149();
|
|
int[][] points = {{1,1},{2,2},{3,3},{4,4},{5,5},{1,2},{2,3},{3,4}};
|
|
int result = solution.maxPoints(points);
|
|
System.out.println("Maximum number of points on a line: " + result);
|
|
}
|
|
} |