第一題
題解:模擬題
class Solution {
public:
int countVowelSubstrings(string w) {
int n = w.length();
int i = 0, res = 0;
string p = "aeiou";
while(i < n){
if(p.find(w[i]) != -1){
int j = i;
while(j < n && p.find(w[j]) != -1){
if(j < i+4) {
j++;
continue;
}
string s = w.substr(i, j-i+1);
set<char> set;
for(auto c : s){
if(!set.count(c)){
set.insert(c);
}
}
if(set.size() >=5){
res++;
}
j++;
}
}
i++;
}
return res;
}
};
第二題
題解:不能直接求子集判斷超時,將問題轉化爲求每一個字母被使用的次數,第i個字母會在出現在 (n - i) * (i + 1) 個子串中
class Solution {
public:
long long countVowels(string w) {
string p = "aeiou";
long long res = 0;
for(int i=0; i<w.length(); i++){
if(p.find(w[i]) != -1){
res += (long long)(i+1) *(w.length()-i);
}
}
return res;
}
};
第三題
二分滿足每一個商店商品數量 大於等於 k,通過商品數組中的商品數量計算店鋪數量是否超過 n 來進行二分。
class Solution {
public:
int minimizedMaximum(int n, vector<int>& q) {
int l = 1;
int r = 0;
for(auto c : q) r = max(r, c);
while(l < r){
int mid = l+r >>1;
if(check(q, mid, n)){
r = mid;
}else{
l = mid+1;
}
}
return r;
}
bool check(vector<int> q, int k, int n){
int cnt = 0;
for(auto c : q){
if(c%k == 0){
cnt += c/k;
}else cnt += (c/k)+1;
if(cnt > n) return false;
}
return true;
}
};
第四題
題解:dfs, 注意 路徑中節點值只能計算一次, 另外方法傳遞vector參數使用引用,不用最後一個用例超時了。
#define PII pair<int, int>
class Solution {
public:
unordered_map<int, vector<PII>> g;
int res = 0, maxTimeV;
int maximalPathQuality(vector<int>& values, vector<vector<int>>& edges, int maxTime) {
maxTimeV = maxTime;
for(auto e : edges){
// 無向邊
g[e[0]].push_back({e[1], e[2]});
g[e[1]].push_back({e[0], e[2]});
}
vector<int> path; // 記錄路徑
dfs(values, 0, 0, 0, path);
return res;
}
void dfs(vector<int>& values,int u, int time, int value, vector<int> path){
path.push_back(u);
int prevVal = values[u];
value += values[u];
// 置爲 0,節點只計算一次value
values[u] = 0;
if(u == 0){
res = max(res, value);
}
for(auto c : g[u]){
if(time + c.second > maxTimeV) continue;
dfs(values, c.first, time+c.second, value, path);
}
// 恢復現場
path.pop_back();
values[u] = prevVal;
value -= prevVal;
}
};