我已经尽力了:
package my;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
// [[0,0],[1,1],[1,-1]]
public class Solution {
public static void main(String[] args){
Solution s= new Solution();
Point[] points = new Point[3];
points[0] = new Point(2,3);
points[1] = new Point(3,3);
points[2] = new Point(-5,3);
System.out.println(s.maxPoints(points));
}
public int maxPoints(Point[] points) {
int max = 0;
int size = points.length;
if(size<=2) return size;
// if(size==1) return 1;
for(int i=0;i<size;i++){
HashMap<Double,Integer> map = new HashMap<Double,Integer>();
int same = 0;
int max_infine = 1;
for(int j=i+1;j<size;j++){
if(points[j].x==points[i].x&&points[j].y==points[i].y){
same++;
}else if(points[j].x==points[i].x){
max_infine++;
}else{
double slope = (double)(points[j].y-points[i].y)
/(double)(points[j].x-points[i].x);
if(slope==-0.0||slope==0.0) slope=0.0;
if(map.containsKey(slope)){
map.put(slope, map.get(slope)+1);
}else{
map.put(slope,2);
}
}
}
int localmax = 0;
for(Map.Entry<Double,Integer> entry:map.entrySet()){
if(entry.getValue()>localmax){
localmax = entry.getValue();
}
}
if(max_infine>localmax) localmax = max_infine;
if(localmax==0){
localmax += same+1;
}else{
localmax += same;
}
max = max>localmax?max:localmax;
}
return max;
}
}
这一题,不知为何行不通:
public class Solution {
public static void main(String[] args){
Point[] points = new Point[4];
points[0] = new Point(3,10);
points[1] = new Point(0,2);
points[2] = new Point(0,2);
points[3] = new Point(3,10);
Solution s = new Solution();
s.maxPoints(points);
}
// [[3,10],[0,2],[0,2],[3,10]]
public int maxPoints(Point[] points) {
int size = points.length;
if(size==1) return 1;
int max = 0;
Map<Integer, HashSet<Integer>> isVisited
= new HashMap<Integer, HashSet<Integer>>();
for(int i=0;i<size;i++){
isVisited.put(i, new HashSet<Integer>());
}
for(int i=0;i<size;i++){
for(int j=i+1;j<size;j++){
int cnt = 2;
if(isVisited.get(i).contains(j)) continue;
else isVisited.get(i).add(j);
// base (i,j) --> k
for(int k=j+1;k<size;k++){
if(isline(points[i], points[j], points[k])){
isVisited.get(i).add(k);
isVisited.get(j).add(k);
cnt++;
}
}
max = max<cnt?cnt:max;
}
}
return max;
}
boolean isline(Point i, Point j, Point k){
if(i.x==j.x&&i.y==j.y) return true;
if(i.x==k.x&&i.y==k.y) return true;
if(j.x==k.x&&j.y==k.y) return true;
if(i.x==j.x&&i.x==k.x) return true;
double k1 = (double)(i.y - j.y)/(double)(i.x - j.x);
double k2 = (double)(k.y - j.y)/(double)(k.x - j.x);
if(k1==k2) return true;
else return false;
}
}