Leetcode第308场周赛
第一题:2389. 和有限的最长子序列
分析:要使原序列中能选择的数序列最长,我们所选择的数就要越小,先将数组从小到大排序,然后从小到大累加与之比较即可。
代码:
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<int> answer;
for (int q : queries) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += nums[i];
if (sum > q) {
answer.push_back(i);
break;
}
}
if(sum <= q) answer.push_back(n);
}
return answer;
}
};
第二题:2390. 从字符串中移除星号
分析:定义一个新字符串,遍历原字符串,如果不是“*”号则将该字符加入新字符串,如果遇到“*”则删除此时新字符串的最后一位,即星号的前一位非字符串。最后输出新字符串res。
代码:
class Solution {
public:
string removeStars(string s) {
string res;
for (char c : s) {
if (c != '*') {
res += c;
} else {
res.pop_back();
}
}
return res;
}
};
Acwing第66场周赛
第一题:4606. 奇偶判断
分析:因为是十六进制数,所以输入我们可以设定为字符串,只需判断最后一位数是否为偶数,除以2后取余为0则为偶数,为1则为奇数,与题目相符可以直接输出取余结果。
代码:
#include <iostream>
using namespace std;
int main()
{
string a;
cin >> a;
cout << a[6] % 2;
return 0;
}
第二题:4607. 字母补全
分析:可以用哈希表来存储每个字母分别出现的次数,用vector来存未出现的字母。若存在重复出现的字母则输出 -1;遍历一段26个字母,将“?”转换为vector数组中已保存的未出现过的字母即可。思路参考
代码:
#include <iostream>
#include <cstring>
#include <unordered_set>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
string s;
cin >> s;
unordered_set<char> hash;
vector<char> cs;
for(int i = 25; i < s.size(); i ++ ) {
hash.clear();
bool flag = true;
for(int j = i - 25; j <= i; j ++ ) {
if(s[j] != '?' && hash.count(s[j])) {
flag = false;
break;
}else {
hash.insert(s[j]);
}
}
if(flag) {
cs.clear();
for(char c = 'A'; c <= 'Z'; c ++) {
if(!hash.count(c)) cs.push_back(c);
}
for(int j = i - 25, k = 0; j <= i; j ++ ) {
if(s[j] == '?') s[j] = cs[k ++];
}
for(auto& c: s) if(c == '?') c = 'A';
cout << s << endl;
return 0;
}
}
puts("-1");
return 0;
}