Basic algorithm learning for Stack and queue (EPI)

Source: Internet
Author: User

Although I have been studying for a long time today, I still feel less efficient. In fact, today I did not browse the projects as planned. I went to see other books during the day. You may need a certain number of classic books to prepare for a job. Books cannot be read, and knowledge points are fixed. Therefore, we should begin to review the previous knowledge after we have browsed several books at hand. C ++ knowledge, leetcode questions, operating systems, databases, and network learning notes ~.

1. Implement a stack and return the maximum value of the current stack. Required, returns the maximum operation time complexity O (1 ). The extra space complexity of O (n) can be used.

I have seen the questions before, so I have a new idea. I can use an additional stack to store the maximum value in the current stack.

The simple idea is that when elements enter the stack, the secondary stack is pushed to the maximum value of the current stack at the same time. When elements exit the stack, the secondary stack element is displayed. Obtain the maximum value directly from the secondary stack consumer.

In addition, you can reduce the number of elements pushed into the secondary stack. Only when the elements pushed into the current stack are greater than or equal to the elements at the top of the current secondary stack can the elements be pushed to the top of the secondary stack, when a stack is exited, the top of the stack is popped up only when the element of the stack is equal to the top element of the secondary stack.

In addition, another method that can be optimized in the constant term is to add a number pair to the auxiliary stack. The value of the number pair is the current maximum value and the current maximum value, if the value is equal during push, the second value of the number pair is increased. If the value is equal during pop, the second value in the number pair is subtracted. If the value is reduced to 0, the pop auxiliary stack can be used.

Expansion problem: implement a queue and support the operation to return the current maximum value. Can the time complexity of O (1) be optimized.

This question is still complicated. We need to combine two knowledge to evenly split the time complexity to O (1), and use two stacks that have implemented the maximum operation to simulate the queue, A queue that can reach the maximum returned value of the O (1) complexity.

In fact, the use of deque can also achieve an average cost of O (1), but the analysis of time complexity is complicated.

It is understood that each element can enter and leave D at most once, instead of entering and leaving D for the second time. Therefore, O (1) is evenly distributed ).

2. Calculate the inverse polish expression and return the calculation result.

The stack is constantly pushed into the number. When the operator number is met, two numbers are taken from the digital stack for calculation, and the result is pushed into the digital stack until the calculation is complete, and the calculation results stored in the digital Stack are.

3. the iterative method implements sequential traversal of BST.

Stack iteration implementation is not very complex, and can complete the sequential traversal of the space complexity of O (1.

In addition, the implementation of post-order traversal is the most difficult to implement in the Traversal method of Binary trees Through iteration. Morris's post-order traversal is also difficult to implement.

4. For the random linked list, that is, a chain table of the random pointer field is added in addition to the next field, and the iterative method is used to traverse the random-first order.

The recursive method is easy to implement. Here, let the iterative method use stack to simulate the recursive method.

template <typename T>void search_postings_list(const shared_ptr<node_t<T> > &L) {    stack<shared_ptr<node_t<T> > > s;    int order = 0;    s.emplace(L);    while(!s.empty()) {        shared_ptr<node_t<T> > curr = s.top();        s.pop();        if( curr && curr->order == -1 ) {            curr->order = order++;            s.emplace(curr->next);            s.emplace(curr->jump);        }     }}

5. Use the stack to record the movement of the tower and simulate it.

void transfer(const int &n, array<stack<int>,3> &pegs, const int &from, const int & to, const int &use) {    if(n > 0) {        transfer(n-1,pegs,from,use,to);        pegs[to].push(pegs[from].top());        pegs[from].pop();        cout<<"Move from peg"<<from<<"to peg"<<to<<endl;        transfer(n-1,pegs,use,to,from);    }}void move_tower_hanoi(const int &n) {    array<stack<int>,3> pegs;    for(int i = n;i >= 1;--i) {         pegs[0].push(i);    }    transfer(n,pegs,0,1,2);}

6. all the windows in a row of buildings face the West. When the sun falls, if there is no building higher than the west of a building, the building can see the sun, from the east to the west, calculate all the buildings with sunshine.

Expansion problem: Calculate all buildings with sunshine from the west to the east.

The fundamental idea of the problem is to use the stack to maintain a descending sequence from east to west. An incremental sequence needs to be maintained from the west to the east. The content of the series and the buildings that can see the sun. This method of maintaining monotonic sequences using stacks can reduce the time complexity to O (n) when calculating the maximum histogram area ).

Descending sequence code from east to west

template <typename T>vector<pair<int,T>> examine_buildings_with_sunset(istringstream &sin) {    int idx = 0;//building‘s index    T height;    //Stores(buiding_idx,building_height) pair with sunset views    vector<pair<int,T> > buildings_with_sunset;    while(sin >> height) {        while(buildings_with_sunset.empty() == false && height >= buildings_with_sunset.back().second) {            buildings_with_sunset.pop_back();        }        buildings_with_sunset.emplace_back(idx++,height);    }     return buildings_with_sunset;} 

7. design an algorithm for sorting stacks by using only the push, Pop, empty, and top operations, and opening up additional space without display.

If no extra space is displayed, you can use the stack storage information of recursive function calls to sort the data. For example, the Recursive Implementation Method of insert sorting.

template <typename T>void sort(stack<T> &S) {    if(!S.emtpy()) {        T e = S.top();        S.pop();        sort(S);        insert(S,e);    }}template <typename T>void insert(stack<T> &S,const T &e) {    if(S.empty() || S.top() <= e) {        S.push(e);    }else {        T f = S.top();        S.pop();        insert(S,e);        S.push(f);    }}

8. Simplify the path name of the file containing... And. To the shortest path.

The idea is to keep a stack. When the directory name at the top of the stack is displayed, the directory name at the top of the stack is ignored. In this way, we can get the shortest path. This topic has many boundaries and is a detailed question.

9. Method of sequence traversal BST.

Sequence traversal, that is, breadth-first search, requires queue to complete the function.

10. Use two integers to implement a queue function. [0, 9] can be added to the queue.

First, we can see that this question comes up with an integer as a bit array. Four digits can represent numbers between [0, 15], so they can be used as arrays.

Later, we can see that [0, 9] is more convenient to calculate according to the decimal digit. Each digit in decimal format is [0, 9]. One digit is used as an array, and the other digit is used as the queue length. Note the boundary condition where all values are 0.

Expansion problem: if there is only one integer, you can use one of them to save the length.

11. Use two stacks to implement a queue so that both pop and push share the cost of O (1 ).

One stack is responsible for entering the queue, and the other stack is responsible for popping up the queue.

12. O (1) the application of the queue that returns the queue max value.

The application scenario is that there is now an array, the array is a number pair, the first element represents a timestamp, the second element represents the event traffic, the array has been sorted according to the time stamp, now we need to calculate the maximum traffic from each timestamp to the timestamp + W.

If the direct solution requires traversing the traffic of the current timestamp to the current timestamp + W, the time complexity is O (NW ).

If priority queue is used, the time complexity of O (nlogw) can be optimized because it is implemented by the smallest heap.

If O (1) is used to return the maximum queue, the time complexity of O (n) is optimized.

Basic algorithm learning for Stack and queue (EPI)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.