Approach
Sorting and greedy selection
For Filter Restaurants by Vegan-Friendly, Price and Distance, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 27 lines of C++ from the credited upstream file 1333.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<int> filterRestaurants(vector<vector<int>>& restaurants,4 int veganFriendly, int maxPrice,5 int maxDistance) {6 vector<int> ans;7 vector<vector<int>> filteredRestaurants;8 9 for (const vector<int>& restaurant : restaurants)10 if (restaurant[2] >= veganFriendly && restaurant[3] <= maxPrice &&11 restaurant[4] <= maxDistance)12 filteredRestaurants.push_back(restaurant);13 14 ranges::sort(filteredRestaurants, ranges::less{},15 [](const vector<int>& restaurant) {16 const int rating = restaurant[1];17 const int id = restaurant[0];18 return pair<int, int>{-rating, -id};19 });20 21 for (const vector<int>& restaurant : filteredRestaurants)22 ans.push_back(restaurant[0]);23 24 return ans;25 }26};27