1333. 餐厅过滤器(中等)- LeetCode

题目描述

1333. 餐厅过滤器(中等)- LeetCode_第1张图片

解法

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,c++,leetcode,算法,数据结构)