diff --git a/FindCelebrityClass.cs b/FindCelebrityClass.cs new file mode 100644 index 0000000..5ab2fea --- /dev/null +++ b/FindCelebrityClass.cs @@ -0,0 +1,56 @@ +/* The Knows API is defined in the parent class Relation. + bool Knows(int a, int b); */ + +public class Solution : Relation { + + // TC => O(n) + // SC => O(1) + public int FindCelebrity(int n){ + if(n <= 1) + { + return -1; + } + int celeb = 0; + + for(int i = 0; i< n; i++){ + if(i != celeb && Knows(celeb, i)){ + celeb = i; + } + } + + for(int k = 0; k < n; k++){ + if(k != celeb && (!Knows(k, celeb) || Knows(celeb, k))){ + return -1; + } + } + + return celeb; + } + + // TC => O(n^2) + // SC => O(n) + public int FindCelebrity1(int n) { + if(n <= 1) + { + return -1; + } + int[] relations = new int[n]; + + for(int i = 0; i< n; i++){ + for(int j = 0; j < n; j++){ + if(Knows(i, j)){ + relations[i]--; + relations[j]++; + } + } + } + + for(int i = 0; i < n; i++){ + if(relations[i] == n-1){ + return i; + } + } + + return -1; + } +} \ No newline at end of file diff --git a/MinCostToSupplyWaterClass.cs b/MinCostToSupplyWaterClass.cs new file mode 100644 index 0000000..6176e96 --- /dev/null +++ b/MinCostToSupplyWaterClass.cs @@ -0,0 +1,49 @@ +// TC => O(n+mlog(n+m)) +// SC => O(n+m) +public class Solution { + int[] uf; + public int MinCostToSupplyWater(int n, int[] wells, int[][] pipes) { + if(n == 0){ + return 0; + } + uf = new int[n + 1]; + for(int i = 0; i< n+1; i++){ + uf[i] = i; + } + + List edges = new List(); + for(int i = 0; i< n; i++){ + edges.Add([0, i+1, wells[i]]); + } + + foreach(var pipe in pipes){ + edges.Add(pipe); + } + + edges.Sort(Comparer.Create((a,b) => + { + return a[2] - b[2]; + })); + + int total = 0; + foreach(var edge in edges){ + int x = edge[0]; + int y = edge[1]; + int cost = edge[2]; + int px = Find(x); + int py = Find(y); + if(px != py){ + total += cost; + uf[px] = py; + } + } + return total; + } + public int Find(int x){ + if(x != uf[x]){ + uf[x] = Find(uf[x]); + } + + return uf[x]; + } +}