Guest User

Untitled

a guest
Jun 25th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. function Node(val) {
  2. this.val = val
  3. this.rightCount = 1
  4. this.left = null
  5. this.right = null
  6. }
  7.  
  8. /**
  9. * @param {number} k
  10. * @param {number[]} nums
  11. */
  12. var KthLargest = function(k, nums) {
  13. this.k = k
  14. this.root = new Node(nums[0])
  15. let i = 1
  16. while(i < nums.length) {
  17. this.addNode(nums[i], this.root)
  18. i++
  19. }
  20. };
  21.  
  22. KthLargest.prototype.addNode = function (val, current) {
  23. if (val < current.val) {
  24. if (current.left) {
  25. this.addNode(val, current.left)
  26. } else {
  27. current.left = new Node(val)
  28. }
  29. } else {
  30. current.rightCount += 1
  31. if (current.right) {
  32. this.addNode(val, current.right)
  33. } else {
  34. current.right = new Node(val)
  35. }
  36. }
  37. }
  38.  
  39. KthLargest.prototype.find = function (current, k) {
  40. if (current) {
  41. if (current.rightCount === k) {
  42. return current
  43. } else if (current.rightCount > k) {
  44. return this.find(current.right, k)
  45. } else {
  46. return this.find(current.left, k - current.rightCount)
  47. }
  48. } else {
  49. return null
  50. }
  51. }
  52.  
  53. /**
  54. * @param {number} val
  55. * @return {number}
  56. */
  57. KthLargest.prototype.add = function(val) {
  58. this.addNode(val, this.root)
  59. var result = this.find(this.root, this.k)
  60. return result ? result.val : null
  61. };
  62.  
  63. /**
  64. * Your KthLargest object will be instantiated and called as such:
  65. * var obj = Object.create(KthLargest).createNew(k, nums)
  66. * var param_1 = obj.add(val)
  67. */
Add Comment
Please, Sign In to add comment