232场周赛
class Solution { // 暴力
public:
bool areAlmostEqual(string s1, string s2) {
int len = s1.length();
int cnt = 0;
int idx1 = 0, idx2 = 0;
string temp;
if (s1 == s2) return true;
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
temp = s1;
char c = s1[i];
temp[i] = temp[j];
temp[j] = c;
if (temp == s2) return true;
}
}
return false;
}
};
class Solution { // 最大度数的点
public:
int findCenter(vector<vector<int>>& edges) {
int n = edges.size();
map<int, int> m;
int max = 0, idx = -1;
for (int i = 0; i < n; i++) {
int a = edges[i][0], b = edges[i][1];
if (m.count(a))
m[a]++;
else {
m[a] = 1;
}
if (max < m[a]) max = m[a], idx = a;
if (m.count(b))
m[b]++;
else {
m[b] = 1;
}
if (max < m[b]) max = m[b], idx = b;
}
return idx;
}
};
class Solution { // 自定义结构体的排序 + 优先队列
typedef struct Class{
double pass, total;
bool operator < (const Class &x) const{
double a = (pass + 1) / (total + 1) - pass/total;
double b = (x.pass + 1) / (x.total + 1) - x.pass / x.total;
return a < b;
}
}C;
public:
double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {
int n = classes.size();
priority_queue<C> pq;;
for (int i = 0; i < n; i++) {
pq.push(C{(double)classes[i][0],(double)classes[i][1]});
}
while (extraStudents) {
C c = pq.top();
pq.pop();
c.pass = c.pass + 1;
c.total = c.total + 1;
pq.push(c);
extraStudents--;
}
double ans = 0;
while (pq.size()) {
C x = pq.top();
pq.pop();
//cout << x.pass << x.total << endl;
ans += (x.pass) / (x.total);
}
return ans / n;
}
};
class Solution {// 双向优先队列
// 类似的题目:直方图中最大的矩形
public:
int maximumScore(vector<int>& nums, int k) {
int n = nums.size();
vector<int> h(n + 2, - 1), l(n + 2), r(n + 2), stk(n + 2);
for (int i = 1; i <= n; i++) h[i] = nums[i - 1];
int tt = 0;
stk[0] = 0;
for (int i = 1; i <= n; i++) {
while (h[stk[tt]] >= h[i] ) tt--; // 栈顶当前元素比h[i]大就先弹栈
l[i] = stk[tt]; // s记录i的左向 第一个比h[i]小的元素下标
stk[++tt] = i; // 将当前元素压栈
}
// 相当于逆向来了一遍求左向的过程
tt = 0;
stk[0] = n + 1;
for (int i = n; i; i--) {
while (h[stk[tt]] >= h[i] ) tt--; // 栈顶当前元素比h[i]大就先弹栈
r[i] = stk[tt]; // s记录i的左向 第一个比h[i]小的元素下标
stk[++tt] = i; // 将当前元素压栈
}
k++; // 因为下标都被扩大了1 所以+1
int res = 0;
for (int i = 1; i <= n; i++) {
if (l[i] < k && r[i] > k)
res = max(res, (r[i] - l[i] + 1 - 2) * h[i]);
}
return res;
}
};