Skip to content

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

  • Time: $O(n^3)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  vector<int> filterRestaurants(vector<vector<int>>& restaurants,
                                int veganFriendly, int maxPrice,
                                int maxDistance) {
    vector<int> ans;
    vector<vector<int>> filteredRestaurants;

    for (const vector<int>& restaurant : restaurants)
      if (restaurant[2] >= veganFriendly && restaurant[3] <= maxPrice &&
          restaurant[4] <= maxDistance)
        filteredRestaurants.push_back(restaurant);

    ranges::sort(filteredRestaurants, ranges::less{},
                 [](const vector<int>& restaurant) {
      const int rating = restaurant[1];
      const int id = restaurant[0];
      return pair<int, int>{-rating, -id};
    });

    for (const vector<int>& restaurant : filteredRestaurants)
      ans.push_back(restaurant[0]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public List<Integer> filterRestaurants(int[][] restaurants, int veganFriendly, int maxPrice,
                                         int maxDistance) {
    return Arrays.stream(restaurants)
        .filter(r -> r[2] >= veganFriendly && r[3] <= maxPrice && r[4] <= maxDistance)
        .sorted(Comparator.comparingInt((int[] r) -> - r[1]).thenComparingInt((int[] r) -> - r[0]))
        .map(r -> r[0])
        .collect(Collectors.toList());
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def filterRestaurants(
      self,
      restaurants: list[list[int]],
      veganFriendly: int,
      maxPrice: int,
      maxDistance: int,
  ) -> list[int]:
    restaurants.sort(key=lambda x: (-x[1], -x[0]))
    return [i for i, _, v, p, d in restaurants
            if v >= veganFriendly and p <= maxPrice and d <= maxDistance]