这个想法是,制作一个二叉搜索树,这可以在 O(log N) 中完成,但在最坏的情况下 O(N) [其中 N - 在这种情况下是总节点/数组元素]。
现在我们可以进行中序遍历,以排序的顺序获取所有元素,这可以做到O(N) [证明:Complexities of binary tree traversals]
现在遍历已排序的元素 K 次(降序);
因此,整体复杂度为:O(N) + O(N) + O(K) => O(N+K)
实施:
public class Solution{
static class BST{
int val;
BST left, right;
public BST(int val) {
this.val = val;
this.left = this.right = null;
}
}
// making bst from the array elements
static BST add(BST root, int item) {
if(root == null) return new BST(item);
if(root.val > item)
root.left = add(root.left, item);
else root.right = add(root.right, item);
return root;
}
// doing inorder to get all elements in sorted order
static void inorder(BST root, List<Integer> list) {
if(root.left != null)
inorder(root.left, list);
list.add(root.val);
if(root.right != null)
inorder(root.right, list);
}
public static void main(String[] args) {
//Example: N = 5, K = 2 Input: 5 6 8 9 3 Output: 9 8
int [] a = {1, 9, 2, 7, 3, -1, 0, 5, 11};
BST root = null;
for(int i=0; i<a.length; i++) {
root = add(root, a[i]);
}
List<Integer> list = new ArrayList<Integer>();
inorder(root, list);
// process the list K times, to get K-th largest elements
}
注意:如果出现重复值,您必须为每个节点制作子列表!