Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions FindCelebrityClass.cs
Original file line number Diff line number Diff line change
@@ -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;
}
}
49 changes: 49 additions & 0 deletions MinCostToSupplyWaterClass.cs
Original file line number Diff line number Diff line change
@@ -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<int[]> edges = new List<int[]>();
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<int[]>.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];
}
}