思路:遍历即可,不满足条件则答案++
class Solution {
public:
int minNumberOfHours(int initialEnergy, int initialExperience, vector<int>& energy, vector<int>& experience) {
int res = 0;
for(int i = 0; i < energy.size(); i++){
if(initialEnergy > energy[i] && initialExperience > experience[i]){
initialEnergy -= energy[i];
initialExperience += experience[i];
}
else{
while(initialEnergy <= energy[i]){
res++;
initialEnergy++;
}
while(initialExperience <= experience[i]){
res++;
initialExperience++;
}
initialEnergy -= energy[i];
initialExperience += experience[i];
}
}
return res;
}
};
第二题:2384. 最大回文数字
思路:用一个数组来统计各个数字出现的次数,将出现偶数次的放入s1一半并删除,注意题目要求不能有前导0的特殊情况,然后再从大到小遍历一次看是否还有可以放入的,然后将s1赋给s2并将s2倒转即可
class Solution {
public:
string largestPalindromic(string num) {
int sum[10] = {0};
for(char s : num) sum[s - '0']++;//统计数字出现的次数
string s1,s2;//s1表示前一半,s2表示后一半,即s1的倒序
for(int i = 9; i >= 0; i--){
if(i == 0 && s1.empty()) break;
int t = sum[i] / 2;
for(int j = 0; j < t; j++){
s1.push_back(i + '0');
}
sum[i] -= t*2;
}
s2 = s1;
reverse(s2.begin(),s2.end());
for(int i = 9; i >= 0; i--){
if(sum[i]){
s1.push_back(i + '0');
break;
}
}
return s1 + s2;
}
};