Last active
October 11, 2021 16:35
-
-
Save JustinChristensen/c05a3482fe22687336dbeef378f89076 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct tree { | |
struct tree_node *root, minimum; | |
size_t size; | |
}; | |
struct tree ktree = { 0 }; | |
// within the loop | |
if (size(ktree) < k) { | |
struct tree_node *n = new_node(arr[i]); | |
insert(n, ktree); | |
continue; | |
} | |
struct tree_node *min = find_min(ktree); | |
if (key(min) < arr[i]) { | |
delete(min, ktree); | |
struct tree_node *n = min; | |
set_key(arr[i], n); | |
insert(n, ktree); | |
} | |
// find_min(ktree) O(1), insert and delete maintain a pointer to the minimum element in the ktree to avoid the O (log k) lookup | |
// insert(n, ktree), delete(n, ktree) O(log k) | |
// space complexity: k nodes total, k total allocations |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment