LeetCode 1333. 餐厅过滤器(Lambda排序)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 1333. 餐厅过滤器(Lambda排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給你一個餐館信息數組 restaurants,其中 restaurants[i] = [idi, ratingi, veganFriendlyi, pricei, distancei]。你必須使用以下三個過濾器來過濾這些餐館信息。
其中素食者友好過濾器 veganFriendly 的值可以為 true 或者 false,如果為 true 就意味著你應該只包括 veganFriendlyi 為 true 的餐館,為 false 則意味著可以包括任何餐館。
此外,我們還有最大價格 maxPrice 和最大距離 maxDistance 兩個過濾器,它們分別考慮餐廳的價格因素和距離因素的最大值。
過濾后返回餐館的 id,按照 rating 從高到低排序。如果 rating 相同,那么按 id 從高到低排序。簡單起見, veganFriendlyi 和 veganFriendly 為 true 時取值為 1,為 false 時,取值為 0 。
示例 1: 輸入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 1, maxPrice = 50, maxDistance = 10 輸出:[3,1,5] 解釋: 這些餐館為: 餐館 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] 餐館 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] 餐館 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] 餐館 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] 餐館 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] 在按照 veganFriendly = 1, maxPrice = 50 和 maxDistance = 10 進行過濾后, 我們得到了餐館 3, 餐館 1 和 餐館 5(按評分從高到低排序)。 示例 2: 輸入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 50, maxDistance = 10 輸出:[4,3,2,1,5] 解釋:餐館與示例 1 相同,但在 veganFriendly = 0 的過濾條件下,應該考慮所有餐館。示例 3: 輸入:restaurants = [[1,4,1,40,10],[2,8,0,50,5],[3,8,1,30,4],[4,10,0,10,3],[5,1,1,15,1]], veganFriendly = 0, maxPrice = 30, maxDistance = 3 輸出:[4,5]提示: 1 <= restaurants.length <= 10^4 restaurants[i].length == 5 1 <= idi, ratingi, pricei, distancei <= 10^5 1 <= maxPrice, maxDistance <= 10^5 veganFriendlyi 和 veganFriendly 的值為 0 或 1 。 所有 idi 各不相同。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/filter-restaurants-by-vegan-friendly-price-and-distance
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution { public:vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) {int i;vector<vector<int>> temp;if(veganFriendly==1){for(i = 0; i < restaurants.size(); ++i){if(restaurants[i][2]==1 && restaurants[i][3]<=maxPrice && restaurants[i][4]<=maxDistance)temp.push_back(restaurants[i]);}}else{for(i = 0; i < restaurants.size(); ++i){if(restaurants[i][3]<=maxPrice && restaurants[i][4]<=maxDistance)temp.push_back(restaurants[i]);}}sort(temp.begin(),temp.end(),[](const auto& a, const auto& b){if(a[1]==b[1])return a[0] > b[0];return a[1] > b[1];});//lambda匿名函數,自定義排序vector<int> ans;for(const auto& r : temp)ans.push_back(r[0]);return ans;} };總結
以上是生活随笔為你收集整理的LeetCode 1333. 餐厅过滤器(Lambda排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 542. 01 矩阵(
- 下一篇: LeetCode 85. 最大矩形(DP