1792. 最大平均通过率
- 有的题似乎只能用优先队列做,其他方法都会超时。比如上面这道。因为之前优先队列做得少,吃了大亏。
- 数据类型包含两个数的,优先使用pair,而非vector。
pair
class Solution {
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
auto cmp = [](const pair<int, int> &p, const pair<int, int> &q) {
auto getV1 = [](const pair<int, int> &p) {
unsigned long x1 = p.first, y1 = p.second;
return double(x1-y1)/x1/(x1+1);
};
return getV1(p) < getV1(q);
};
priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> heap(cmp);
for (const auto &v : classes) {
heap.emplace(v[1], v[0]);
}
for (int i = 0; i < extraStudents; ++i) {
pair<int, int> t = heap.top();
heap.pop();
heap.emplace(t.first + 1, t.second + 1);
}
double ret = 0.0;
while (!heap.empty()) {
pair<int, int> t = heap.top();
heap.pop();
ret += (double)t.second / t.first;
}
return ret / classes.size();
}
};
vector
class Solution {
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
int n=classes.size();
auto fun=[](vector<int>&a){
return double (1.0*(a[1]-a[0])/(a[1])/(a[1]+1));
};
auto comp=[&](vector<int>* x,vector<int>* y){return fun(*x)<fun(*y);};
priority_queue<vector<int>*,vector<vector<int>*>,decltype(comp)>Q(comp);
for(int i=0;i<n;i++)Q.push(&classes[i]);
while(extraStudents--){
auto cur=Q.top();
Q.pop();
(*cur)[0]++;
(*cur)[1]++;
Q.push(cur);
}
double sum=0;
for(int i=0;i<n;i++){
sum+=double(classes[i][0])/classes[i][1];
}
return sum/n;
}
};