前言
昨天做了没发,昨天是个简单的排序题,今天过滤餐厅,主要还是得重写java比较器,最近的排序很多都是用到重写比较器,还是需要多练习
题目
源码
class Solution {
public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice, int maxDistance) {
List <int[]>tmp = new ArrayList<>();//储存满足条件的餐厅
List<Integer>ans = new ArrayList<>();
for(int []a:restaurants){
if(a[2]>=veganFriendly && a[3]<=maxPrice && a[4]<=maxDistance){//过滤得到合格的餐厅
tmp.add(a);
}
}
Collections.sort(tmp,new Comparator<int[]>(){
public int compare(int[] a,int[] b){//重写比较器,当rate相同时,按id排序,默认按rate排
if(a[1]==b[1]){
return b[0]-a[0];
}
return b[1]-a[1];
}
});
for(int i=0;i<tmp.size();i++){//得到餐厅id
ans.add(tmp.get(i)[0]);
}
return ans;
}
}