โจทย์
A generic Stack<T> works for any type. Here you extend the idea: a stack of integers that can also report its minimum in constant time.
Process the operations in order:
push <x>: push x.pop: remove the top value (ignored when the stack is empty).min: report the smallest value currently in the stack, or -1 if it is empty.
Implement min_stack_operations(operations).
Input
operations: The operations.
Output
Return the answers of the min operations, in order.
เงื่อนไข
1 ≤ number of operations ≤ 200,000
0 ≤ x ≤ 10^9
ตัวอย่าง
อินพุต:
operations = ["push 5", "push 3", "min", "pop", "min"]
ผลลัพธ์ที่คาดหวัง:
expected = [3, 5]
อินพุต:
std::vector<std::string> operations = {"push 5", "push 3", "min", "pop", "min"};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {3, 5};
อินพุต:
string[] operations = new string[] {"push 5", "push 3", "min", "pop", "min"};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {3, 5};
คำอธิบาย
With 5 and 3 on the stack the minimum is 3. After popping 3, only 5 is left: [3, 5].
อินพุต:
operations = ["min", "pop", "push 7", "min"]
ผลลัพธ์ที่คาดหวัง:
expected = [-1, 7]
อินพุต:
std::vector<std::string> operations = {"min", "pop", "push 7", "min"};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {-1, 7};
อินพุต:
string[] operations = new string[] {"min", "pop", "push 7", "min"};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {-1, 7};
คำอธิบาย
The empty stack reports -1 and the pop is ignored; then the minimum is 7: [-1, 7].
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Store, next to each value, the minimum of the stack at that point.
คำใบ้ 2
The current minimum is then simply the top of that second stack.
คำใบ้ 3
Ignore pop on an empty stack, and answer -1 for min when it is empty.
ความซับซ้อนที่คาดหวัง
O(number of operations) time, O(number of operations) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน