Created
June 24, 2018 22:35
-
-
Save revanth0212/ca92c787180efcc292559e36ba448cd7 to your computer and use it in GitHub Desktop.
Find the Kth largest element in a stream using a BST.
This file contains hidden or 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
function Node(val) { | |
this.val = val | |
this.rightCount = 1 | |
this.left = null | |
this.right = null | |
} | |
/** | |
* @param {number} k | |
* @param {number[]} nums | |
*/ | |
var KthLargest = function(k, nums) { | |
this.k = k | |
this.root = new Node(nums[0]) | |
let i = 1 | |
while(i < nums.length) { | |
this.addNode(nums[i], this.root) | |
i++ | |
} | |
}; | |
KthLargest.prototype.addNode = function (val, current) { | |
if (val < current.val) { | |
if (current.left) { | |
this.addNode(val, current.left) | |
} else { | |
current.left = new Node(val) | |
} | |
} else { | |
current.rightCount += 1 | |
if (current.right) { | |
this.addNode(val, current.right) | |
} else { | |
current.right = new Node(val) | |
} | |
} | |
} | |
KthLargest.prototype.find = function (current, k) { | |
if (current) { | |
if (current.rightCount === k) { | |
return current | |
} else if (current.rightCount > k) { | |
return this.find(current.right, k) | |
} else { | |
return this.find(current.left, k - current.rightCount) | |
} | |
} else { | |
return null | |
} | |
} | |
/** | |
* @param {number} val | |
* @return {number} | |
*/ | |
KthLargest.prototype.add = function(val) { | |
this.addNode(val, this.root) | |
var result = this.find(this.root, this.k) | |
return result ? result.val : null | |
}; | |
/** | |
* Your KthLargest object will be instantiated and called as such: | |
* var obj = Object.create(KthLargest).createNew(k, nums) | |
* var param_1 = obj.add(val) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment