第 172 场周赛

5315. 6 和 9 组成的最大数字

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
string tostr(int n){
string ret = "";
while(n){
ret += n % 10 + '0';
n /= 10;
}
if(ret == "") ret = "0";
reverse(ret.begin(), ret.end());
return ret;
}
int toint(string n){
int num = 0;
for(int i=0; i<n.size(); i++){
num = num * 10 + n[i]-'0';
}
return num;
}
int maximum69Number (int num) {
string rem = tostr(num);
for(int i=0; i<rem.size(); i++){
if(rem[i] == '6'){
rem[i] = '9';
break;
}
}
return toint(rem);
}
};

1324. 竖直打印单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public:
vector<string> printVertically(string s) {
vector<string> res;
string tmp = "";
int maxlen = 0;
for(int i=0; i<s.size(); i++){
if(s[i] == ' '){
res.push_back(tmp);
maxlen = max(maxlen, (int)tmp.size());
tmp = "";
continue;
}
tmp += s[i];
}
maxlen = max(maxlen, (int)tmp.size());
res.push_back(tmp);
vector<string> ret;
for(int i=0; i<maxlen; i++){
string cur = "";
for(int j=0; j<res.size(); j++){
if(i >= res[j].size()) cur += " ";
else cur += res[j][i];
}
int end = cur.size()-1;
for(; end>=0; end--){
if(cur[end] != ' ')
break;
}
cur = cur.substr(0, end+1);
ret.push_back(cur);
}
return ret;
}
};

1325. 删除给定值的叶子节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* removeLeafNodes(TreeNode* root, int target) {
if(root == NULL) return NULL;
if(!root->left && !root->right && root->val == target)
return NULL;
if(root->left) root->left = removeLeafNodes(root->left, target);
if(root->right) root->right = removeLeafNodes(root->right, target);
if(!root->left && !root->right && root->val == target)
return NULL;
else return root;
}
};

1326. 灌溉花园的最少水龙头数目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minTaps(int n, vector<int>& ranges) {
vector<int> lands(n);
for(int i=0; i<ranges.size(); i++){
int l = max(0, i-ranges[i]);
int r = min(n, i+ranges[i]);
for(int j=l; j<r; j++){
lands[j] = max(lands[j], r);
}
}
int count = 0;
int cur = 0;
while(cur < n){
if(lands[cur] == 0) return -1;
cur = lands[cur];
count++;
}
return count;
}
};
Donate? comment?