【排序】【数组】【2023-09-27】
有一个餐厅数组 resturants,其中 resturants[i] 表示 i 餐厅的基本信息,包括:餐厅 id、餐厅排名、对素食者是否友好、 餐厅的价格以及餐厅的距离。你需要根据是否对素食者友好、最大价格以及最大距离进行筛选。
对素食者是否友好的值为 1 或者 0,1 表示只可以选择对素食者友好的餐厅,0 表示对餐厅没有限制。
过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序
直接按照过滤要求进行过滤,得到筛选后的一些餐厅:
veganFriendly = 0 或者 resturants[i][2] = veganFriendly;此条件判断也可以直接写成 resturants[i][2] >= veganFriendlyresturants[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),使用的额外变量是用来存放筛选结果的数组。
如果文章内容有任何错误或者您对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。
如果大家有更优的时间、空间复杂度方法,欢迎评论区交流。
最后,感谢您的阅读,如果感到有所收获的话可以给博主点一个 👍 哦。