网络编程
位置:首页>> 网络编程>> Go语言>> Go/C语言LeetCode题解997找到小镇法官

Go/C语言LeetCode题解997找到小镇法官

作者:刘09k11  发布时间:2024-05-21 10:18:54 

标签:Go,C语言,LeetCode,小镇法官

题目描述

997. 找到小镇的法官 - 力扣(LeetCode)

小镇里有 n 个人,按从 1n 的顺序编号。传言称,这些人中有一个暗地里是小镇法官。

如果小镇法官真的存在,那么:

  • 小镇法官不会信任任何人。

  • 每个人(除了小镇法官)都信任这位小镇法官。

  • 只有一个人同时满足属性 1 和属性 2 。

给你一个数组 trust ,其中 trust[i] = [ai, bi] 表示编号为 ai 的人信任编号为 bi 的人。

如果小镇法官存在并且可以确定他的身份,请返回该法官的编号;否则,返回 -1

示例 1:

输入:n = 2, trust = [[1,2]]
输出:2

示例 2:

输入:n = 3, trust = [[1,3],[2,3]]
输出:3

示例 3:

输入:n = 3, trust = [[1,3],[2,3],[3,1]]
输出:-1

  提示:

1 <= n <= 1000

0 <= trust.length <= 10^4

trust[i].length == 2[= 

trust 中的所有trust[i] = [ai, bi] 互不相同

ai != bi

1 <= ai, bi <= n

思路分析

记录每个人被信任的次数。 信任次数为n-1的人就是法官

同时如果这个人信任别过人就让他的被信任次数-1 (这个操作主要是判断一个人不是法官,如果一个人被其他人信任了n-1次,那么这个人可能是法官,如果这个人信任过别人,那么让他的被信任次数-1,他的被信任次数为n-2!=n-1。这样就满足了法官不能信别人的逻辑,他也就不是法官。)

有人被信任的次数为n-1,那么他就是法官!没有这样的人,那么返回-1.

go 代码

class Solution {
   public static int findJudge(int n, int[][] trust) {
       int[] times=new int[n+1];
       for(int i=0;i&lt;trust.length;i++){
           times[trust[i][1]]++;
           times[trust[i][0]]--;
       }
       for(int i=1;i&lt;=n;i++){
           if(times[i]==n-1) return i;
       }
       return -1;
   }
}

C语言

暴力法

关键点:

1:关键点两个,一个是相信的人数,一个是不能相信人

2:用hashSet去记录,如果相信别人,那么这个人的信用设置为负数。

3:被相信的人,hashSet信用值增加

时间复杂度:O(n)

空间复杂度:O(n)

代码

int findJudge(int n, int** trust, int trustSize, int* trustColSize)
{
   //根据入度进行遍历
   int hashSet[n+1]; //相信这个i的人数
   memset(hashSet,0, sizeof(hashSet));
   for(int i = 0; i < trustSize; i++)
   {
       hashSet[trust[i][1]]++;
       //相信别人 就不能是法官
       hashSet[trust[i][0]] = INT_MIN;

}
     for(int i = 1; i <= n; i++)
   {
       if(hashSet[i] == n-1 )
       {
           return i;
       }
   }
         return -1;
}

参考

一题两解:哈希表 & 优化! - 找到小镇的法官 - 力扣(LeetCode)

来源:https://juejin.cn/post/7181072544416890935

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com