feat: add Redundant Connection (#1181)

Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
Alexander Pantyukhin 2023-01-18 23:15:47 +04:00 committed by GitHub
parent 78d083fd84
commit 36d1b265a7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 0 deletions

View File

@ -88,6 +88,7 @@
| 647 | [Palindromic Substring](https://leetcode.com/problems/palindromic-substrings/) | [C](./src/647.c) | Medium |
| 669 | [Trim a Binary Search Tree](https://leetcode.com/problems/trim-a-binary-search-tree/) | [C](./src/669.c) | Medium |
| 674 | [Longest Continuous Increasing Subsequence](https://leetcode.com/problems/longest-continuous-increasing-subsequence/) | [C](./src/674.c) | Easy |
| 684 | [Redundant Connection](https://leetcode.com/problems/redundant-connection/description/) | [C](./src/684.c) | Medium |
| 700 | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [C](./src/700.c) | Easy |
| 701 | [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/) | [C](./src/701.c) | Medium |
| 704 | [Binary Search](https://leetcode.com/problems/binary-search/) | [C](./src/704.c) | Easy |

49
leetcode/src/684.c Normal file
View File

@ -0,0 +1,49 @@
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int find(int* sets, int index){
while (sets[index] != index){
index = sets[index];
}
return index;
}
void unionSet(int* sets, int i1, int i2){
int i1Parent = find(sets, i1);
int i2Parent = find(sets, i2);
sets[i1Parent] = i2Parent;
}
// Union find
// Runtime: O(n)
// Space: O(n)
int* findRedundantConnection(int** edges, int edgesSize, int* edgesColSize, int* returnSize){
int setsSize = edgesSize + 1;
int* sets = malloc(setsSize * sizeof(int));
for (int i = 0; i < setsSize; i++){
sets[i] = i;
}
int* result = malloc(2 * sizeof(int));
*returnSize = 2;
for (int i = 0; i < edgesSize; i++){
int* edge = edges[i];
int i0Parent = find(sets, edge[0]);
int i1Parent = find(sets, edge[1]);
if (i0Parent == i1Parent){
result[0] = edge[0];
result[1] = edge[1];
continue;
}
unionSet(sets, i0Parent, i1Parent);
}
free(sets);
return result;
}