Implement Queue
EasyP2Coding
Implement a queue of integers (first in, first out) in which every operation takes O(1) amortized time.
Implement the MyQueue class:
MyQueue()creates an empty queue.enqueue(x)addsxat the back.dequeue()removes and returns the front element, or-1if the queue is empty.front()returns the front element without removing it, or-1if the queue is empty.isEmpty()returnstrueif the queue has no elements.size()returns the number of elements.
Removing from the front of an array with shift() or pop(0) is O(n), so it does not meet the requirement.
Example 1
- Input
- ["MyQueue","enqueue","enqueue","front","dequeue","dequeue","isEmpty"] [[],[1],[2],[],[],[],[]]
- Output
- [null,null,null,1,1,2,true]
- Why
- Elements leave in the order they arrived.
Constraints
- -10^9 <= x <= 10^9
- At most 10^5 calls in total.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 2 visible tests, Submit all 7. ⌘Enter runs, ⌘⇧Enter submits.