这题目很坑爹,这题目的描述就是一个巨坑。一个卧槽已经不能形容我的心情了,mmp。和谐500字。。。。。
先对餐厅距离排升序,找到第n个离人最近的餐厅,把这个距离设为x,然后在从list中依此找距离小于x的餐厅。
给出一个List
,里面的数据代表每一个餐厅的坐标[x, y]
。顾客的坐标处于原点[0, 0]
。先找出n
家离顾客位置最近的餐厅,然后取 n
家先出现在List中且与顾客的距离不超过 n
家离顾客最近的餐厅的最长距离。返回这 n
家餐厅的坐标序列,按输入数据原始的顺序。
样例
给定 : n = 2 , List = [[0,0],[1,1],[2,2]]
返回 : [[0,0],[1,1]]
给定 : n = 3,List = [[0,1],[1,2],[2,1],[1,0]]
返回 :[[0,1],[1,2],[2,1]]
注意事项
1.坐标的范围[-1000, 1000]
2.n > 0
3.不存在相同的坐标
import java.util.*;
public class Solution {
/**
* @param restaurant:
* @param n:
* @return: nothing
*/
public static List<List<Integer>> nearestRestaurant(List<List<Integer>> restaurant, int n) {
// Write your code here
if(restaurant==null||restaurant.size()==0||restaurant.size()<n){
return new ArrayList<>();
}
if(n==restaurant.size())
return restaurant;
List<List<Integer>> temp = new ArrayList<>(restaurant);
Collections.sort(temp, new Comparator<List<Integer>>() {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
int t1=o1.get(0)*o1.get(0)+o1.get(1)*o1.get(1);
int t2=o2.get(0)*o2.get(0)+o2.get(1)*o2.get(1);
if(t1>t2)
return 1;
else if(t1<t2)
return -1;
else
return 0;
}
});
int max = temp.get(n).get(0)*temp.get(n).get(0)+temp.get(n).get(1)*temp.get(n).get(1);
int t1;
int t2;
List<Integer> mmp=new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
for(int i=0;i<restaurant.size();i++){
t1=restaurant.get(i).get(0);
t2=restaurant.get(i).get(1);
if(t1*t1+t2*t2<max){
mmp=restaurant.get(i);
res.add(mmp);
if(res.size()>=n)
return res;
}
}
return res;
}
}