|
| 1 | +/** |
| 2 | + * 1670. Design Front Middle Back Queue |
| 3 | + * https://leetcode.com/problems/design-front-middle-back-queue/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Design a queue that supports push and pop operations in the front, middle, and back. |
| 7 | + * |
| 8 | + * Implement the FrontMiddleBack class: |
| 9 | + * - FrontMiddleBack() Initializes the queue. |
| 10 | + * - void pushFront(int val) Adds val to the front of the queue. |
| 11 | + * - void pushMiddle(int val) Adds val to the middle of the queue. |
| 12 | + * - void pushBack(int val) Adds val to the back of the queue. |
| 13 | + * - int popFront() Removes the front element of the queue and returns it. If the queue is |
| 14 | + * empty, return -1. |
| 15 | + * - int popMiddle() Removes the middle element of the queue and returns it. If the queue is |
| 16 | + * empty, return -1. |
| 17 | + * - int popBack() Removes the back element of the queue and returns it. If the queue is |
| 18 | + * empty, return -1. |
| 19 | + * |
| 20 | + * Notice that when there are two middle position choices, the operation is performed on the |
| 21 | + * frontmost middle position choice. For example: |
| 22 | + * - Pushing 6 into the middle of [1, 2, 3, 4, 5] results in [1, 2, 6, 3, 4, 5]. |
| 23 | + * - Popping the middle from [1, 2, 3, 4, 5, 6] returns 3 and results in [1, 2, 4, 5, 6]. |
| 24 | + */ |
| 25 | + |
| 26 | +var FrontMiddleBackQueue = function() { |
| 27 | + this.elements = []; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number} val |
| 32 | + * @return {void} |
| 33 | + */ |
| 34 | +FrontMiddleBackQueue.prototype.pushFront = function(val) { |
| 35 | + this.elements.unshift(val); |
| 36 | +}; |
| 37 | + |
| 38 | +/** |
| 39 | + * @param {number} val |
| 40 | + * @return {void} |
| 41 | + */ |
| 42 | +FrontMiddleBackQueue.prototype.pushMiddle = function(val) { |
| 43 | + const mid = Math.floor(this.elements.length / 2); |
| 44 | + this.elements.splice(mid, 0, val); |
| 45 | +}; |
| 46 | + |
| 47 | +/** |
| 48 | + * @param {number} val |
| 49 | + * @return {void} |
| 50 | + */ |
| 51 | +FrontMiddleBackQueue.prototype.pushBack = function(val) { |
| 52 | + this.elements.push(val); |
| 53 | +}; |
| 54 | + |
| 55 | +/** |
| 56 | + * @return {number} |
| 57 | + */ |
| 58 | +FrontMiddleBackQueue.prototype.popFront = function() { |
| 59 | + return this.elements.length ? this.elements.shift() : -1; |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * @return {number} |
| 64 | + */ |
| 65 | +FrontMiddleBackQueue.prototype.popMiddle = function() { |
| 66 | + if (!this.elements.length) return -1; |
| 67 | + const mid = Math.floor((this.elements.length - 1) / 2); |
| 68 | + return this.elements.splice(mid, 1)[0]; |
| 69 | +}; |
| 70 | + |
| 71 | +/** |
| 72 | + * @return {number} |
| 73 | + */ |
| 74 | +FrontMiddleBackQueue.prototype.popBack = function() { |
| 75 | + return this.elements.length ? this.elements.pop() : -1; |
| 76 | +}; |
0 commit comments