用Java编写int findJudge(int n, vector<vector<int>>& trust) { vector<int> indegree(n+1, 0); for (const auto& t : trust) { indegree[t[0]]++; } for (int i = 1; i <= n; i++) { if (indegree[i] == 0) return i; } return -1; }
时间: 2023-02-07 12:24:46 浏览: 69
首先,我们来简要回顾一下这道题目的题意。
给定一个整数 n 和一个包含 n 个元素的二维数组 trust,trust[i] 表示第 i 个人信任的人的编号。
如果某个人 x 信任某个人 y,那么 y 将会是 x 的管理者。所有人都有管理者,除了一个人,这个人是所有人的管理者。对于这道题目,你需要实现一个函数,找出所有人的管理者。
下面是 Java 代码的示例实现:
```
public int findJudge(int n, int[][] trust) {
// 创建一个数组,用来记录每个人被信任的次数
int[] trustCount = new int[n + 1];
// 遍历 trust 数组,记录每个人被信任的次数
for (int[] t : trust) {
trustCount[t[1]]++;
}
// 遍历 trustCount 数组,找到被所有人信任的人
for (int i = 1; i <= n; i++) {
if (trustCount[i] == n - 1) {
return i;
}
}
// 如果没有找到,返回 -1
return -1;
}
```
希望这个示例能够帮助你。
相关问题
vector<int> &a 与vector<int>&a的区别
vector<int> &a 和 vector<int>&a 的区别在于空格的位置。在第一个表达式中,空格位于类型名称 vector<int> 和引用符号 & 之间,而在第二个表达式中,空格位于引用符号 & 和变量名称 a 之间。实际上,这两个表达式是等价的,都表示一个引用类型的 vector<int> 变量。
vector<int> eventualSafeNodes(vector<vector<int>> &graph)
graph) {
int n = graph.size();
vector<int> indegrees(n, 0); // indegrees[i] stores the indegree of node i
vector<vector<int>> adjList(n, vector<int>()); // adjList[i] stores the nodes that have an edge from i
queue<int> q; // queue for BFS
// Build adjacency list and indegrees
for (int i = 0; i < n; i++) {
for (int j : graph[i]) {
adjList[i].push_back(j);
indegrees[j]++;
}
}
// Add nodes with indegree 0 to the queue
for (int i = 0; i < n; i++) {
if (indegrees[i] == 0) {
q.push(i);
}
}
// BFS
while (!q.empty()) {
int curr = q.front();
q.pop();
for (int next : adjList[curr]) {
indegrees[next]--;
if (indegrees[next] == 0) {
q.push(next);
}
}
}
// Add nodes with indegree 0 to the result
vector<int> res;
for (int i = 0; i < n; i++) {
if (indegrees[i] == 0) {
res.push_back(i);
}
}
return res;
}