Skip to content

Commit d06adfe

Browse files
committed
update 308.md
1 parent b92165e commit d06adfe

File tree

1 file changed

+117
-0
lines changed

1 file changed

+117
-0
lines changed

Diff for: leetcode/weekly/308.md

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
### T1
2+
贪心
3+
```c++
4+
class Solution {
5+
public:
6+
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
7+
sort(begin(nums), end(nums));
8+
vector <int> ans;
9+
for (int q: queries) {
10+
int j = 0, tot = 0;
11+
while(j < nums.size()) {
12+
tot += nums[j++];
13+
if(tot == q) break;
14+
if(tot > q) {
15+
j--;
16+
break;
17+
}
18+
}
19+
ans.push_back(j);
20+
}
21+
return ans;
22+
}
23+
};
24+
```
25+
26+
### T2
27+
模拟栈
28+
```c++
29+
class Solution {
30+
public:
31+
string removeStars(string s) {
32+
string ans;
33+
for (char c: s) {
34+
if(c == '*' && ans.size()) ans.pop_back();
35+
else ans += c;
36+
}
37+
return ans;
38+
}
39+
};
40+
```
41+
42+
### T3
43+
简单模拟,总之就是中规中矩
44+
```c++
45+
class Solution {
46+
public:
47+
int garbageCollection(vector<string>& a, vector<int>& b) {
48+
int n = a.size();
49+
vector <vector<int>> cnt(3, vector <int> (n));
50+
for (int i = 0; i < n; i++) {
51+
for (char c: a[i]) {
52+
if(c == 'G') cnt[0][i]++;
53+
if(c == 'M') cnt[1][i]++;
54+
if(c == 'P') cnt[2][i]++;
55+
}
56+
}
57+
int ans = 0;
58+
for (int i = 0; i < 3; i++) {
59+
ans += cnt[i][0];
60+
int last = 0;
61+
for (int j = 1; j < n; j++){
62+
if(cnt[i][j]) ans += cnt[i][j], last = j;
63+
}
64+
for (int j = 0; j < last; j++) ans += b[j];
65+
}
66+
return ans;
67+
}
68+
};
69+
```
70+
71+
### T4
72+
记录状态依赖关系,可以通过拓扑排序跑一次确定下来
73+
```c++
74+
class Solution {
75+
public:
76+
vector<vector<int>> buildMatrix(int k, vector<vector<int>>& a, vector<vector<int>>& b) {
77+
int n = a.size(), m = b.size();
78+
vector <vector<int>> g1(k + 1), g2(k + 1);
79+
vector <int> dg1(k + 1), dg2(k + 1);
80+
for (auto & a: a) {
81+
g1[a[0]].push_back(a[1]);
82+
dg1[a[1]]++;
83+
}
84+
for (auto & b: b) {
85+
g2[b[0]].push_back(b[1]);
86+
dg2[b[1]]++;
87+
}
88+
auto get = [&](vector <vector<int>> & g, vector <int> & dg)->vector<int> {
89+
queue <int> q;
90+
for (int i = 1; i <= k; i++) {
91+
if(dg[i] == 0) q.push(i);
92+
}
93+
int level = 0, cnt = 0;
94+
vector <int> ans(k + 1);
95+
while(q.size()) {
96+
auto u = q.front(); q.pop();
97+
ans[u] = level++;
98+
cnt++;
99+
for (int v: g[u]) {
100+
if(--dg[v] == 0) {
101+
q.push(v);
102+
}
103+
}
104+
}
105+
if(cnt != k) return {};
106+
return ans;
107+
};
108+
vector <vector<int>> ans(k, vector <int> (k));
109+
auto a1 = get(g1, dg1), a2 = get(g2, dg2);
110+
if(a1.empty() || a2.empty()) return {};
111+
for (int i = 1; i <= k; i++) {
112+
ans[a1[i]][a2[i]] = i;
113+
}
114+
return ans;
115+
}
116+
};
117+
```

0 commit comments

Comments
 (0)