2017.10.30
就是先算出每个点到目标点的距离,然后按距离排序。
当距离相等的时候,按照x,y的值进行排序。
最后,输出前k个就可以了。
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
/*
* @param points: a list of points
* @param origin: a point
* @param k: An integer
* @return: the k closest points
*/
public Point[] kClosest(Point[] points, Point origin, int k) {
// write your code here
HashMap<Integer,LinkedList<Point>> map = new HashMap<>();
for(Point p : points){
//System.out.println("Point p = [" + p.x + "," + p.y +"]" );
int distance = getDistance(p,origin);
if(!map.containsKey(distance) == true){
LinkedList<Point> list = new LinkedList<>();
list.add(p);
map.put(distance, list);
}
else{
map.get(distance).add(p);
}
}
//printMap(map);
int[] key = new int[map.keySet().size()];
int tmp = 0;
for(int i : map.keySet()){
key[tmp++] = i;
}
Arrays.sort(key);
//System.out.println("zheli");
int count = 0;
Point[] res = new Point[k];
for(int i = 0 ; i < key.length; i++){
LinkedList<Point> listTmp = map.get(key[i]);
listTmp = sort(listTmp);
for(Point p :listTmp){
res[count] = p;
//System.out.println("加入[" + p.x + "," + p.y +"]" );
count++;
if(count >= k){
return res;
}
}
}
return res;
}
public LinkedList<Point> sort(LinkedList<Point> list){
if(list.isEmpty() || list.size() == 1){
return list;
}
LinkedList<Point> res = new LinkedList<>();
for(Point p : list){
if(res.isEmpty()){
res.add(p);
}
else{
res.add(p);
for(int i = res.size() - 2; i >= 0; i--){
Point p2 = res.get(i);
if(p.x > p2.x){
continue;
}
if(p.x == p2.x && p.y >= p2.y){
continue;
}
res.set(i+1, p2);
if(p.x < p2.x){
res.set(i,p);
}
else if(p.x == p2.x && p.y <= p2.y){
res.set(i,p);
}
}
}
}
return res;
}
public int getDistance(Point point, Point origin) {
// write your code here
int a = point.x - origin.x;
int b = point.y - origin.y;
return a*a + b*b;
}
}