mirror of
https://github.moeyy.xyz/https://github.com/TheAlgorithms/C.git
synced 2023-10-11 15:56:24 +08:00
feat: add Redundant Connection (#1181)
Co-authored-by: David Leal <halfpacho@gmail.com>
This commit is contained in:
parent
78d083fd84
commit
36d1b265a7
@ -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
49
leetcode/src/684.c
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user