题目来源
题目描述
题目解析
注意:
- 如果存在法官,那么所有人都会信任法官,在结合条件1,可以得出信任法官的人数为n-1。
- 如果不存在法官,那么也可能存在某些人被所有人信任,这个人的信任人数也为n-1,但是他也会信任别人。
根据题意找到出度为0且入度为n-1的那个人编号即可。
统计出度&&入度即可
class Solution {
public:
int findJudge(int n, vector<vector<int>>& trust) {
std::vector<int> out(n + 1), in(n + 1);
for(auto it : trust){
out[it[0]]++;
in[it[1]]++;
}
for(int i = 1; i < in.size(); ++i){
//找到满足条件的就是法官,遍历完没找到则法官不存在返回-1
if(out[i] == 0 && in[i] == n-1) return i;
}
return -1;
}
};
生成图
根据题意找到出度为0且入度为n-1的那个人编号即可。
class Solution {
struct Edge;
struct Node;
struct Graph;
struct Node{
int val;
int in;
int out;
std::vector<std::shared_ptr<Node>> nexts;
std::vector<std::shared_ptr<Edge>> edges;
Node(int val, int in, int out) : val(val), in(in), out(out){
}
};
struct Edge{
int weight{};
std::shared_ptr<Node> from;
std::shared_ptr<Node> to;
Edge(int weight, std::shared_ptr<Node> &from, std::shared_ptr<Node>& to) : weight(weight),from(from), to(to){
}
};
struct Graph{
std::map<int, std::shared_ptr<Node>> nodes;
std::set<std::shared_ptr<Edge>> edges;
};
std::set<std::shared_ptr<Node>> maybeAns;
std::shared_ptr<Graph> createGraph(vector<vector<int>>& trust){
std::shared_ptr<Graph> graph = std::make_shared<Graph>();
for (auto & i : trust) {
int from = i[0], to = i[1];
if(!graph->nodes.count(from)){
graph->nodes[from] = std::make_shared<Node>(from, 0, 0);
}
if(!graph->nodes.count(to)){
graph->nodes[to] = std::make_shared<Node>(to, 0, 0);
}
std::shared_ptr<Node> fromNode = graph->nodes[from], toNode = graph->nodes[to];
std::shared_ptr<Edge> newEdge = std::make_shared<Edge>(0, fromNode, toNode);
fromNode->out++;
toNode->in++;
fromNode->nexts.emplace_back(toNode);
fromNode->edges.emplace_back(newEdge);
graph->edges.emplace(newEdge);
maybeAns.erase(fromNode);
if(toNode->out == 0){
maybeAns.emplace(toNode);
}else{
maybeAns.erase(toNode);
}
}
return graph;
}
public:
int findJudge(int n, vector<vector<int>>& trust) {
if(trust.empty()){
if(n == 1){
return 1;
}
return -1;
}
maybeAns.clear();
auto graph = createGraph(trust);
for(auto &i : maybeAns){
if(i->in == n - 1){
return i->val;
}
}
return -1;
}
};