Programming beauty 3.7
The queue has only two common operations: enqueue (V) and dequeue (V). Here, you need to add an operation that takes the maximum value and minimize the time complexity.
Considering the previous issue of designing the maximum value for the stack, you only need to use another stack to record the maximum value in the current stack, if the number of elements in the stack is greater than that in the stack, the maximum value is updated. When the number of elements in the stack is equal to that in the stack, the maximum number of elements in the stack is recorded at the same time.
The queue is much more complicated to implement this function, and it is possible to use the stack to realize the maximum value of the queue.
Two stacks A and B are used to simulate the queuing and queuing operations. When the two stacks A and B are in the queue, the elements are directly put into the stack. When the two stacks are in the queue, the system first checks whether stack B is empty, if it is null, the elements in stack a are pushed out of stack B in sequence, and an element is removed from Stack B.
Use a stack C and D respectively to record the maximum values of stack a and stack B. the maximum value of the entire queue should be the maximum values of stack a and stack B.
1 # Include <iostream> 2 # Include <vector> 3 Using Namespace STD; 4 5 # Define Min-999999 6 7 Vector < Int > A, B; 8 Vector < Int > C, D; 9 Void Initial () 10 { 11 C. push_back (min ); 12 D. push_back (min ); 13 } 14 15 Void Push ( Int T) 16 { 17 A. push_back (t ); 18 If (T> C. Back ()) 19 C. push_back (t ); 20 } 21 22 Int Pop () 23 { 24 Int T; 25 If (B. Empty ()) 26 { 27 While (! A. Empty ()) 28 { 29 T = A. Back (); 30 A. pop_back (); 31 If (T = C. Back ()) 32 C. pop_back (); 33 B. push_back (t ); 34 If (T> D. Back ()) 35 D. push_back (t ); 36 } 37 } 38 T = B. Back (); 39 If (T = D. Back ()) 40 D. pop_back (); 41 B. pop_back (); 42 Return T; 43 } 44 45 Int Getmax () 46 { 47 Return C. Back ()> D. Back ()? C. Back (): D. Back (); 48 } 49 50 Int Main () 51 { 52 Initial (); 53 Push ( 1 ); 54 Cout <getmax () < Endl; 55 Push ( 5 ); 56 Cout <getmax () < Endl; 57 Push ( 3 ); 58 Cout <getmax () < Endl; 59 Push ( 4 ); 60 Cout <getmax () < Endl; 61 While (! A. Empty () |! B. Empty ()) 62 { 63 Cout <POP () < " " ; 64 Cout <getmax () < Endl; 65 } 66 Return 0 ; 67 }