【每日一题】餐厅过滤器

Tag

【排序】【数组】【2023-09-27】


题目来源

1333. 餐厅过滤器


题目解读

有一个餐厅数组 resturants,其中 resturants[i] 表示 i 餐厅的基本信息,包括:餐厅 id、餐厅排名、对素食者是否友好、 餐厅的价格以及餐厅的距离。你需要根据是否对素食者友好、最大价格以及最大距离进行筛选。

对素食者是否友好的值为 1 或者 01 表示只可以选择对素食者友好的餐厅,0 表示对餐厅没有限制。

过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序


解题思路

方法一:过滤+排序

直接按照过滤要求进行过滤,得到筛选后的一些餐厅:

  • veganFriendly = 0 或者 resturants[i][2] = veganFriendly;此条件判断也可以直接写成 resturants[i][2] >= veganFriendly
  • resturants[i][3] <= maxPrice
  • resturants[i][4] <= maxDistance

以上三个条件同时满足,餐厅 resturants[i] 会被筛选留下来。

将筛选得到的数组 res 中元素按照排名作为第一关键字,id 作为第二关键字进行降序排序。

从前往后枚举记录 res 中的 id 到答案数组 ans 中,最后返回 ans

实现代码

class Solution {
public:
    vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
        vector<vector<int>> res;
        for (auto restaurant : restaurants) {
            if ((veganFriendly == 0 || veganFriendly == restaurant[2]) && restaurant[3] <= maxPrice && restaurant[4] <= maxDistance) {
                res.push_back(restaurant);
            }
        }

        sort(res.begin(), res.end(), [&](const vector<int>& a, const vector<int>& b) {
            return a[1] == b[1] ? a[0] > b[0] : a[1] > b[1];
        });

        vector<int> ans;
        for (auto re : res) {
            ans.push_back(re[0]);
        }
        return ans;
    }
};

复杂度分析

时间复杂度: O ( n l o g n ) O(nlogn) O(nlogn) n n n 为数组 resturants 的长度。

空间复杂度: O ( n ) O(n) O(n),使用的额外变量是用来存放筛选结果的数组。


写在最后

如果文章内容有任何错误或者您对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。

如果大家有更优的时间、空间复杂度方法,欢迎评论区交流。

最后,感谢您的阅读,如果感到有所收获的话可以给博主点一个 👍 哦。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang_nn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值