6134. 找到离给定两个节点最近的节点
class Solution {
public:
int closestMeetingNode(vector<int>& e, int n1, int n2) {
int n = e.size();
vector< vector<int> > d (2, vector<int>(n,INT_MAX) );
int dis = 0;
vector<int> vis(n,0);
for( int v = n1;v!=-1 && vis[v] ==0; v = e[v]){
vis[v] = 1;
d[0][v] = dis++;
}
fill(vis.begin(),vis.end(),0);
dis = 0;
for( int v = n2;v!=-1 && vis[v] ==0; v = e[v]){
vis[v] = 1;
d[1][v] = dis++;
}
int ret = INT_MAX;
int v = -1;
for(int i=0;i<n;++i){
if( max<int>(d[0][i],d[1][i]) < ret){
ret = max<int>(d[0][i],d[1][i]);
v = i;
}
}
return v;
}
};
使数组中所有元素都等于0
class Solution {
public:
int minimumOperations(vector<int>& a) {
sort(a.begin(),a.end());
int n = unique(a.begin(),a.end())-a.begin();
if(a[0]==0){
--n;
}
return n;
}
};
分组的最大数量
class Solution {
public:
int maximumGroups(vector<int>& a) {
int n = a.size();
int i=1;
for(i = 1; i*(i+1)/2 <= n ; ++i);
return i-1;
}
};
图中最长的环
class Solution {
public:
int longestCycle(vector<int>& e) {
int n = e.size();
vector<int> v(n,0);
int ret = -1;
for(int i=0;i<n;++i){
if( v[i]==0 ){
unordered_map<int,int> rd;
int index = 1;
int x = i;
while( x!=-1 ){
if( rd.count(x) > 0 ){
ret = max<int>(ret, index-rd[x] );
}
if(v[x] == 1){
break;;
}
v[x] = 1;
rd[x] = index;
x = e[x];
++index;
}
}
}
return ret;
}
};