一、LeetCode 308
1、2389.和有限的最长子序列
(1)原题链接:力扣
https://leetcode.cn/problems/longest-subsequence-with-limited-sum/
(2)解题思路:
先对nums数组进行一个排序,以便于我们选取最长子序列,我们只需要从头开始遍历累加直到当前累加值大于等于queries中的元素,然后统计遍历的位置即最长子序列的长度。
(3)代码:
class Solution {
public:
vector<int> answerQueries(vector<int>& nums, vector<int>& queries) {
vector<int> res;
sort(nums.begin(), nums.end());
for(auto& x: queries) {
int idx = 0;
int cmp = 0;
bool flag = false;
for(int i = 0; i < nums.size(); i ++ ) {
cmp += nums[i];
if(cmp > x) {
idx = i;
flag = true;
break;
}
}
if(flag == false) res.push_back(nums.size());
else res.push_back(idx - 0);
}
return res;
}
};
2、2390.从字符串中移除星号
(1)原题链接:
力扣https://leetcode.cn/problems/removing-stars-from-a-string/
(2)解题思路:
从头开始遍历,每当遇到 * 时就删除答案字符串的最后一个元素即可。
(3)代码:
class Solution {
public:
string removeStars(string s) {
string res;
for(auto& ch: s) {
if(ch != '*') res += ch;
else res.pop_back();
}
return res;
}
};
3、2391.收集垃圾的最少总时间
(1)原题链接:力扣
https://leetcode.cn/problems/minimum-amount-of-time-to-collect-garbage/
(2)解题思路:
由题可知,每辆垃圾车都是独立的,所以求总的最小时间就是求每辆垃圾车的最小时间,而每辆垃圾车所花费的时间 = 每个地点该种垃圾的数量处理花费的时间 + 路上的时间。因此,我们只需要求出垃圾车最终到达的地点在哪,然后再遍历到达该地点花费的时间 以及 我们处理垃圾所花费的时间即可。
(3)代码:
class Solution {
public:
int garbageCollection(vector<string>& garbage, vector<int>& travel) {
string op = "MPG";
int res = 0;
for(auto& c: op) {
int k = 0;
for(int i = 0; i < garbage.size(); i ++ ) {
int cnt = 0;
for(auto x : garbage[i]) {
if(c == x) cnt ++;
}
res += cnt;
if(cnt) k = i;
}
for(int i = 0; i < k; i ++ ) res += travel[i];
}
return res;
}
};
二、AcWing 66
1、4606.奇偶判断
(1)原题链接:4606. 奇偶判断 - AcWing题库
(2)解题思路:
直接使用字符串输入,然后取字符串的最后一位数将其转换为整型数据,然后再判断奇偶性即可。
(3)代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
string s;
cin >> s;
int tmp = 0;
for(int i = s.size() - 1; i >= 0; i --) {
tmp = s[i] - '0';
break;
}
if(tmp % 2) cout << 1 << endl;
else cout << 0 << endl;
return 0;
}
2、4607.字母补全
(1)原题链接:4607. 字母补全 - AcWing题库
(2)解题思路:
用哈希表来存每26个字母出现的次数,用vector来存每26个字母中未出现的字母。
第一步,先保存出现过的字母,若存在重复出现则直接输出 -1;
第二步,遍历某段26个字母,将 ?转换为 vector 中保存的字母。
(3)代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_set>
#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;
}