Non-Leetcode Questions: Two Closest Points to a Given Point
Find the 2 points from a list that are closest to a given point. Distance is calculated using Euclidean distance.
public List<Point> twoClosestPointsToAGivenPoint(List<Point> list, Point given){
if(list.size() < 2){return list;}
List<Point> rlst = new ArrayList<Point>();
Point first = list.get(0);
Point second = list.get(1);
double f_distance = dis(first, given);
double s_distance = dis(second, given);
for(int i = 2;i < list.size();i++){
double distance = dis(list.get(i),given);
if(distance < s_distance){
if(distance < f_distance){
second = first;
s_distance = f_distance;
first = list.get(i);
f_distance = distance;
}else{
second = list.get(i);
s_distance = distance;
}
}
}
rlst.add(first);
rlst.add(second);
return rlst;
}
private double dis(Point a, Point b){
return Math.pow(a.x-b.x,2)+Math.pow(a.y-b.y,2);
}
Read full article from Non-Leetcode Questions: Two Closest Points to a Given Point
Find the 2 points from a list that are closest to a given point. Distance is calculated using Euclidean distance.
public List<Point> twoClosestPointsToAGivenPoint(List<Point> list, Point given){
if(list.size() < 2){return list;}
List<Point> rlst = new ArrayList<Point>();
Point first = list.get(0);
Point second = list.get(1);
double f_distance = dis(first, given);
double s_distance = dis(second, given);
for(int i = 2;i < list.size();i++){
double distance = dis(list.get(i),given);
if(distance < s_distance){
if(distance < f_distance){
second = first;
s_distance = f_distance;
first = list.get(i);
f_distance = distance;
}else{
second = list.get(i);
s_distance = distance;
}
}
}
rlst.add(first);
rlst.add(second);
return rlst;
}
private double dis(Point a, Point b){
return Math.pow(a.x-b.x,2)+Math.pow(a.y-b.y,2);
}
Read full article from Non-Leetcode Questions: Two Closest Points to a Given Point