总结
果然,参加比赛的时候确实比较憨哈哈。第一题可以直接暴力,当然其实可以转化成找不同的非0数的个数,考试没想出来QAQ。第二题可以发现,排序之后,第一个条件一定满足,我们只需要比较数量,可惜比赛的时候比较憨写了一个双指针,其实找规律就可以了hh。第三题和第四题是基环树模型,当然可以通过dfs或者bfs思想直接做就可以了,当然可以使用强联通分量的算法,不过没有必要hh。
6132. 使数组中所有元素都等于零
class Solution {
public:
int minimumOperations(vector<int>& nums) {
set<int> s;
for (auto a : nums)
if (a)
s.insert(a);
return s.size();
}
};
6133. 分组的最大数量
class Solution {
public:
int maximumGroups(vector<int>& grades) {
int k = 1;
int n = grades.size();
while ((k + 1) * k / 2 <= n) k ++ ;
return k - 1;
}
};
6134. 找到离给定两个节点最近的节点
class Solution {
public:
int closestMeetingNode(vector<int> &edges, int node1, int node2) {
int n = edges.size(), min_dis = n, ans = -1;
auto calc_dis = [&](int x) {
vector<int> dis(n, n);
for (int d = 0; x >= 0 && dis[x] == n; x = edges[x])
dis[x] = d++;
return dis;
};
auto d1 = calc_dis(node1), d2 = calc_dis(node2);
for (int i = 0; i < n; ++i) {
int d = max(d1[i], d2[i]);
if (d < min_dis) {
min_dis = d;
ans = i;
}
}
return ans;
}
};
6135. 图中的最长环
class Solution {
public:
int longestCycle(vector<int> &edges) {
int n = edges.size(), time[n], ans = -1;
memset(time, 0, sizeof(time));
for (int i = 0, clock = 1; i < n; ++i) {
if (time[i]) continue;
for (int x = i, start_time = clock; x >= 0; x = edges[x]) {
if (time[x]) { // 重复访问
if (time[x] >= start_time) // 找到了一个新的环
ans = max(ans, clock - time[x]);
break;
}
time[x] = clock++;
}
}
return ans;
}
};