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

题目描述

在这里插入图片描述

解法

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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值