Leetcode算法题2301-2400


2301-2310

2311-2320

2315. 统计星号

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int countAsterisks(string s) {
int cnt = 0;
bool valid = true;
for (auto &it: s) {
if (it == '|') valid = !valid;
else if (it == '*' && valid) cnt += 1;
}
return cnt;
}
};

2319. 判断矩阵是否是一个 X 矩阵

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool checkXMatrix(vector<vector<int>>& grid) {
int len=grid.size();
for(int i=0;i<len;++i){
for(int j=0;j<len;++j){
if(i==j||len-j-1==i){
if(!grid[i][j]) return false;
}else{
if(grid[i][j]) return false;
}
}
}
return true;
}
};

2321-2330

2325. 解密消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string decodeMessage(string key, string message) {
char map[26];
memset(map, 0, sizeof map);
stringstream res;
int index = 0;
for (int i = 0; i < key.length(); ++i) {
if (key[i] != ' ' && map[key[i] - 'a'] == 0) {
map[key[i] - 'a'] = 'a' + index++;
}
}
for (char &it: message) {
if (it == ' ') res.put(' ');
else res.put(map[it - 'a']);
}
return res.str();
}
};

2331-2340

2331.计算布尔二叉树的值

1
2
3
4
5
6
7
8
class Solution {
public:
bool evaluateTree(TreeNode *root) {
if (root->val == 2) return evaluateTree(root->left) || evaluateTree(root->right);
if (root->val == 3) return evaluateTree(root->left) && evaluateTree(root->right);
return root->val;
}
};

2341-2350

2351-2360

2357.使数组中所有元素都等于零

1
2
3
4
5
6
7
8
9
10
11
// 本题的解题思路在于将问题明确,选择小于等于非0的最小元素,因为每次减多了也只会变成0。
// 因此每次直接选择减去等于非0的最小元素,就是最少的次数。
// 于是本题就转化为了存在多少个不同的非0元素个数
class Solution {
public:
int minimumOperations(vector<int>& nums) {
unordered_map<int,bool> heap;
for(auto &it:nums) if(it) heap[it]=true;
return heap.size();
}
};

文章作者: 不二
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 不二 !
  目录