标签:traints highlight ice 餐厅 therefore 参数 NPU || str
问题:
给出一组餐厅各种参数的,餐厅排行榜,
根据用户提供的3个要求:Vegan-Friendly, Price ,Distance
过滤满足要求的餐厅,并按照餐厅排行榜排序,若排名ranking一样,则按照id排序(都是大的排在前面)。
Example 1: Input: 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 Output: [3,1,5] Explanation: The restaurants are: Restaurant 1 [id=1, rating=4, veganFriendly=1, price=40, distance=10] Restaurant 2 [id=2, rating=8, veganFriendly=0, price=50, distance=5] Restaurant 3 [id=3, rating=8, veganFriendly=1, price=30, distance=4] Restaurant 4 [id=4, rating=10, veganFriendly=0, price=10, distance=3] Restaurant 5 [id=5, rating=1, veganFriendly=1, price=15, distance=1] After filter restaurants with veganFriendly = 1, maxPrice = 50 and maxDistance = 10 we have restaurant 3, restaurant 1 and restaurant 5 (ordered by rating from highest to lowest). Example 2: Input: 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 Output: [4,3,2,1,5] Explanation: The restaurants are the same as in example 1, but in this case the filter veganFriendly = 0, therefore all restaurants are considered. Example 3: Input: 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 Output: [4,5] Constraints: 1 <= restaurants.length <= 10^4 restaurants[i].length == 5 1 <= idi, ratingi, pricei, distancei <= 10^5 1 <= maxPrice, maxDistance <= 10^5 veganFriendlyi and veganFriendly are 0 or 1. All idi are distinct.
解法:
遍历餐厅排行榜,选出满足3个条件的餐厅,保存ranking和id到结果res数组
然后使用sort函数,进行降序排序
首先比较ranking,ranking降序排序,
若ranking一样,则比较id,id降序排序。
代码参考:
1 class Solution { 2 public: 3 static bool comp(const vector<int>& a, const vector<int>&b){ 4 return (a[1]==b[1])?a[0]>b[0]:a[1]>b[1]; 5 } 6 vector<int> filterRestaurants(vector<vector<int>>& restaurants, int veganFriendly, int maxPrice, int maxDistance) { 7 vector<vector<int>> res;//{res[i][0]=id,res[i][1]=rating} 8 vector<int> resid; 9 for(vector<int> rst:restaurants){ 10 if(((veganFriendly==1 && rst[2]==1) || (veganFriendly==0)) && rst[3]<=maxPrice && rst[4]<=maxDistance){ 11 res.push_back({rst[0], rst[1]}); 12 } 13 } 14 sort(res.begin(), res.end(), comp); 15 for(auto a:res){ 16 resid.push_back(a[0]); 17 } 18 return resid; 19 } 20 };
1333. Filter Restaurants by Vegan-Friendly, Price and Distance
标签:traints highlight ice 餐厅 therefore 参数 NPU || str
原文地址:https://www.cnblogs.com/habibah-chang/p/13287720.html