🔗 leetcode.com/problems/mo…
题目
- 给若干商品的价格和美观度,求指定 query 下,满足 query ≥ price 的美观度最大值;
思路
- 非官方提示的思路,因为把题目的美观度最大值当成了美观度的求和,不过按照这个思路修改代码后,不影响解题;
- 对商品按照价格进行排序,提前计算好,某个商品 i 前的美观度最大值 pre_max;
- 给定 query,对商品进行二分查找,找到 price[i] ≤ query 的 i 的最大值,即商品 i 价值前的 price 都满足条件;
- 返回此时美观度的最大值;
踩坑
- 排序 sort 的自定义函数,需要满足严格弱关系,即如果 a == b,需要返回 false;
- 自定义函数需要为 return a < b 或者 return a > b ;
代码
class Solution {
public:
static bool cmp_item(vector<int>& a, vector<int>& b) {
return a[0] < b[0]
}
int upper_found(vector<vector<int>>& items, vector<int>& pre_max, int found) {
if (found < items[0][0]) return 0
int l = 0, r = items.size()-1
int index = 0
while (l < r) {
int mid = (l + r) >> 1
if (items[mid][0] > found) r = mid -1
else if (items[mid][0] < found) l = mid + 1
else l = mid +1
}
if (items[l][0] > found) l--
return pre_max[l]
}
vector<int> maximumBeauty(vector<vector<int>>& items, vector<int>& queries) {
sort(items.begin(), items.end(), cmp_item)
vector<int> pre_max(items.size())
pre_max[0] = items[0][1]
int index = 1
for (int index = 1
pre_max[index] = max(pre_max[index-1], items[index][1])
}
vector<int> ans
for (int i = 0
ans.push_back(upper_found(items, pre_max, queries[i]))
}
return ans
}
}