[JavaScript] using datastrucutres-js/priority-queue, min and max
LeetCode provides the JavaScript environment with 2 packages from NPM to assist with data structures, datastructures-js/priority-queue and datastructures-js/que
LeetCode provides the JavaScript environment with 2 packages from NPM to assist with data structures, `datastructures-js/priority-queue` and `datastructures-js/queue`.\n\nhttps://support.leetcode.com/hc/en-us/articles/360011833974-What-are-the-environments-for-the-programming-languages-\n\nthe API for `priority-queue` is intuitive and well documented. (the only thing I found not well documented is that when you poll using `.dequeue()` or `.front()`, it returns an object with properties `priority` and `element`. in our use case, these values will both equal the element, but imagine that the element you put in was a linked list node, such as in #23 Merge k Sorted Lists - then your priority will be whatever you configure your PQ to use (in that case, ListNode().val), and element will be the ListNode. The imporant takeaway for this problem is to follow all calls `.dequeue()` or `.front()` with `.element`.)\n\nhttps://github.com/datastructures-js/priority-queue\n\nas for the algorithm itself, just check other top posts, it\'s implemented the same with the 2 step addNum() process of insertion and balancing.\n\n```\nvar MedianFinder = function() {\n    // to find median in O(1) time, we will split all numbers coming in into\n    // 2 Priority Queues - all input from lowest -> median will be stored in \n    // max, and all input from median -> highest will be stored in min. this\n    // means that the .front().element of min and max will be in the middle.\n\n    const max = new MaxPriorityQueue();\n    const min = new MinPriorityQueue();\n    \n    return { addNum, findMedian }\n    \n    function addNum(num) {\n        if (min.front() != null && num < min.front().element)\n            max.enqueue(num)\n        else\n            min.enqueue(num)\n        \n        const diff = min.size() - max.size()\n        if (diff > 1) \n            max.enqueue(min.dequeue().element)\n        if (diff < -1) \n            min.enqueue(max.dequeue().element)\n    }\n    \n    function findMedian() {\n        const diff = min.size() - max.size()\n        if (diff > 0)\n            return min.front().element\n        else if (diff < 0)\n            return max.front().element\n        else\n            return (min.front().element + max.front().element)/2\n    }\n}\n```
[]