[LeetCode] Filter Restaurants by Vegan-Friendly, Price and Distance

1333. Filter Restaurants by Vegan-Friendly, Price and Distance

Given the array restaurants where restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]. You have to filter the restaurants using three filters.

The veganFriendly filter will be either true (meaning you should only include restaurants with veganFriendlyi set to true) or false (meaning you can include any restaurant). In addition, you have the filters maxPrice and maxDistance which are the maximum value for price and distance of restaurants you should consider respectively.

Return the array of restaurant IDs after filtering, ordered by rating from highest to lowest. For restaurants with the same rating, order them by id from highest to lowest. For simplicity veganFriendlyi and veganFriendly take value 1 when it is true, and 0 when it is false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {
vector<pair<int, int>> A;
for(auto& r : restaurants) {
int id = r[0], ra = r[1], f = r[2], p = r[3], d = r[4];
if(f >= veganFriendly and p <= maxPrice and d <= maxDistance)
A.push_back({ra, id});
}
sort(rbegin(A), rend(A));
vector<int> res;
for(auto& [_, id] : A)
res.push_back(id);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/18/PS/LeetCode/filter-restaurants-by-vegan-friendly-price-and-distance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.