| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FindTheTownJudge; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindTheTownJudgeIterative : IFindTheTownJudge |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n^2 + t) |
| | 19 | | /// Space complexity - O(n + t) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <param name="trust"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int FindJudge(int n, int[][] trust) |
| 5 | 25 | | { |
| 5 | 26 | | if (trust.Length == 0) |
| 2 | 27 | | { |
| 2 | 28 | | if (n > 1) |
| 1 | 29 | | { |
| 1 | 30 | | return -1; |
| | 31 | | } |
| | 32 | |
|
| 1 | 33 | | return 1; |
| | 34 | | } |
| | 35 | |
|
| 3 | 36 | | var sum = n * (n + 1) / 2; |
| | 37 | |
|
| 3 | 38 | | var judges = new Dictionary<int, HashSet<int>>(); |
| | 39 | |
|
| 21 | 40 | | foreach (var t in trust) |
| 6 | 41 | | { |
| 6 | 42 | | if (!judges.TryAdd(t[1], [t[0]])) |
| 2 | 43 | | { |
| 2 | 44 | | judges[t[1]].Add(t[0]); |
| 2 | 45 | | } |
| 6 | 46 | | } |
| | 47 | |
|
| 11 | 48 | | foreach (var judge in judges.Where(j => |
| 11 | 49 | | j.Value.Sum() == sum - j.Key && !judges.Any(v => v.Value.Contains(j.Key)))) |
| 2 | 50 | | { |
| 2 | 51 | | return judge.Key; |
| | 52 | | } |
| | 53 | |
|
| 1 | 54 | | return -1; |
| 5 | 55 | | } |
| | 56 | | } |