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
class Solution {
 public:
  vector<int> filterRestaurants(vector<vector<int>>& restaurants,
                                int veganFriendly, int maxPrice,
                                int maxDistance) {
    vector<int> ans;
    vector<vector<int>> filtered;

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

    ranges::sort(filtered, [](const vector<int>& a, const vector<int>& b) {
      return a[1] == b[1] ? a[0] > b[0] : a[1] > b[1];
    });

    for (const vector<int>& f : filtered)
      ans.push_back(f[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((a, b) -> a[1] == b[1] ? Integer.compare(b[0], a[0]) : Integer.compare(b[1], a[1]))
        .map(i -> i[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]