Skip to content

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

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);

    sort(begin(filtered), end(filtered), [](const auto& a, const auto& b) {
      return a[1] == b[1] ? a[0] > b[0] : a[1] > b[1];
    });

    for (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] ? b[0] - a[0] : b[1] - a[1])
        .map(i -> i[0])
        .collect(Collectors.toList());
  }
}
1
2
3
4
class Solution:
  def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
    restaurants.sort(key=lambda r: (-r[1], -r[0]))
    return [i for i, _, v, p, d in restaurants if v >= veganFriendly and p <= maxPrice and d <= maxDistance]