第 324 场周赛
1.统计相似字符串对的数目
Solution
class Solution {
public:
int similarPairs(vector<string>& words) {
unordered_map<int,int> book;
int len1 = words.size();
int ans = 0;
for(int i = 0;i < len1;i++){
string s = words[i];
//定义一个数代表要表示的字符组成
int bit = 0;
for(int j = 0;j < s.size();j++){
bit |= (1 << (s[j] - 'a'));
}
ans += book[bit]++;
}
return ans;
}
};
2.使用质因数之和替换后可以取到的最小值
Solution
class Solution {
public:
int smallestValue(int n) {
int i = 2;
int ans = 0;
while(1){
i = 2;
ans = 0;
int x = n;
while(i*i <= x){
if(x % i == 0){
x /= i;
ans += i;
while(x % i == 0){
ans += i;
x /= i;
}
}
i++;
}
if(x > 1) ans += x;
//cout<<ans<<" "<<endl;
if(n == ans) break;
n = ans;
}
return n;
}
};
3.添加边使所有节点度数都为偶数
Solution
因为最多只能加两条边,情况有限,分类讨论就行
class Solution {
public:
bool isPossible(int n, vector<vector<int>>& edges) {
unordered_set<int> g[n+1];
for(auto e: edges){
int x = e[0];
int y = e[1];
g[x].insert(y);
g[y].insert(x);
}
vector<int> odd;
//度为奇的点放入
for(int i = 0;i <= n;i++){
if(g[i].size() % 2){
odd.push_back(i);
}
}
//开始分类讨论
int s = odd.size();
if(s == 0) return true;
if(s == 2){//两个点度为奇数则,
int x = odd[0];int y = odd[1];
if(!g[x].count(y)) return true;
for(int i = 1;i <= n;i++){
if(i != x && i != y && !g[i].count(x) && !g[i].count(y)){
return true;
}
}
return false;
}
if(s == 4){
int x = odd[0],y = odd[1], m = odd[2], k = odd[3];
return !g[x].count(y) && !g[m].count(k) ||
!g[x].count(m) && !g[y].count(k) ||
!g[x].count(k) && !g[y].count(m);
}
return false;
}
};
4.查询树中环的长度
Solution
找最小公共祖先就行
class Solution {
public:
vector<int> cycleLengthQueries(int n, vector<vector<int>>& queries) {
int m = queries.size();
vector<int> ans(m);
//对点进行向上查找
for(int i = 0;i < m;i++){
int t = 1,a = queries[i][0], b = queries[i][1];
while(a != b){
a > b? a /= 2 : b /= 2;
t++;
}
ans[i] = t;
}
return ans;
}
};