跳到主要内容

2582.递枕头

链接:2582.递枕头
难度:Easy
标签:数学、模拟
简介:过滤后返回餐馆的 id,按照 rating 从高到低排序。如果 rating 相同,那么按 id 从高到低排序。

题解 1 - cpp

  • 编辑时间:2023-09-27
  • 执行用时:88ms
  • 内存消耗:26.94MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
vector<pair<int, int>> list;
for (auto &item : restaurants) {
if (item[3] <= maxPrice && item[4] <= maxDistance and (!veganFriendly || item[2])) {
list.push_back(make_pair(item[0], item[1]));
}
}
sort(list.begin(), list.end(), [&](auto &a, auto &b) {
return a.second != b.second ? a.second < b.second : a.first < b.first;
});
reverse(list.begin(), list.end());
vector<int> res;
for (auto &item : list) res.push_back(item.first);
return res;
}
};

题解 2 - python

  • 编辑时间:2023-09-27
  • 执行用时:64ms
  • 内存消耗:23.1MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
restaurants = [item for item in restaurants if item[3] <=
maxPrice and item[4] <= maxDistance and (not veganFriendly or item[2])]
restaurants.sort(key=lambda item: (item[1], item[0]), reverse=True)
return [item[0] for item in restaurants]

题解 3 - rust

  • 编辑时间:2023-09-27
  • 执行用时:8ms
  • 内存消耗:3.11MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn filter_restaurants(
restaurants: Vec<Vec<i32>>,
vegan_friendly: i32,
max_price: i32,
max_distance: i32,
) -> Vec<i32> {
let mut restaurants: Vec<Vec<i32>> = restaurants
.into_iter()
.filter(|item| {
item[3] <= max_price
&& item[4] <= max_distance
&& (vegan_friendly == 0 || item[2] == 1)
})
.collect();
restaurants.sort_by(|item1, item2| {
if item1[1] != item2[1] {
item2[1].cmp(&item1[1])
} else {
item2[0].cmp(&item1[0])
}
});
restaurants.into_iter().map(|item| item[0]).collect()
}
}