题目描述

解法
Python代码参考了题解区大佬的解法,主要用了以下两个Python内置函数,比较方便:
- filter()函数
- sorted()函数
Python代码:
class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
def isVeganFriendly(restaurant):
if veganFriendly == 0:
return True
else:
return restaurant[2] == 1
def belowMaxPrice(restaurant):
return restaurant[3] <= maxPrice
def belowMaxDistance(restaurant):
return restaurant[4] <= maxDistance
restaurants = list(filter(isVeganFriendly,restaurants))
restaurants = list(filter(belowMaxDistance,restaurants))
restaurants = list(filter(belowMaxPrice,restaurants))
return [restaurant[0] for restaurant in sorted(restaurants,key=lambda x:(x[1],x[0]),reverse=True)]
C++版本的代码,参考题解区:
class Solution {
public:
vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
//筛选符合条件的餐厅
vector<vector<int>> ans;
for(int i=0;i<restaurants.size();++i)
if((veganFriendly==0||restaurants[i][2]==veganFriendly) && restaurants[i][3]<=maxPrice && restaurants[i][4]<=maxDistance)
ans.push_back(restaurants[i]);
//按照题目中规定的id和rating规则排序
sort(ans.begin(),ans.end(),[](auto &a,auto &b){
if(a[1]==b[1])
return a[0]>b[0];
else
return a[1]>b[1];
});
//从排序好的容器中筛选出id存入新的容器m,然后返回m
vector<int> m;
for(int i=0;i<ans.size();++i)
m.push_back(ans[i][0]);
return m;
}
};
- LeetCode&spm=1001.2101.3001.5002&articleId=108228184&d=1&t=3&u=4cef41ba47394dd88a43e8064715cfa9)
829

被折叠的 条评论
为什么被折叠?



