1.优先队列
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> q;
for (int s: stones) {
q.push(s);
}
while (q.size() > 1) {
int a = q.top();
q.pop();
int b = q.top();
q.pop();
if (a > b) {
q.push(a - b);
}
}
return q.empty() ? 0 : q.top();
}
};
2.贪心,推理
class Solution {
public:
int fillCups(vector<int>& amount) {
sort(amount.begin(), amount.end());
if (amount[0] + amount[1] <= amount[2]) return amount[2];
else {
int t = amount[0] + amount[1] - amount[2];
return (t + 1) / 2 + amount[2];
}
}
};
3.简单的推理即可。
class Solution {
public:
int maximumScore(int a, int b, int c) {
if(a+b<=c){
return a+b;
}
else if(a+c<=b){
return a+c;
}
else if(b+c<=a){
return b+c;
}
else{
return (a+b+c)/2;
}
}
};
4.贪心
class Solution {
public:
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
priority_queue<int> pq;
int ans = 0, prev = 0, fuel = startFuel;
int n = stations.size();
for (int i = 0; i <= n; i++) {
int curr = i < n ? stations[i][0] : target;
fuel -= curr - prev;
while (fuel < 0 && !pq.empty()) {
fuel += pq.top();
pq.pop();
ans++;
}
if (fuel < 0) {
return -1;
}
if (i < n) {
pq.emplace(stations[i][1]);
prev = curr;
}
}
return ans;
}
};