"Common Algorithm Thinking Analysis series" stack and queue high-frequency problem sets (modified version)

Source: Internet
Author: User

This article is the third of "common Algorithm Thinking Analysis series", Analysis stack and queue-related high-frequency topics. This paper analyzes: 1, can query the most value of the stack, 2, with two stacks to achieve the function of the queue, 3, reverse the elements in the stack, 4, sorting the elements in the stack, 5, sliding window problems.
Top two navigation in this series:
"Common Algorithm Thinking Analysis series" Sorting high Frequency problem sets
"Common Algorithm Thinking Analysis series" string high frequency problem set


1, can query the most value of the stack

Define the data structure of the stack, implement a min function that can get the smallest element of the stack in the type.

Ideas:Define two stacks stackdata and Stackmin, where Stackdata is used to store the data in the stack, and stackmin is used to store the minimum value during the stack. Scenario One: When the stack element is currently being <=stackmin to the top of the stack element, the current to the stack element is added to the stackmin at the same time, when the stack element is currently >stackmin the top element, Stackmin stack does not press into the data;
Scenario two: When currently going into the stack element <=stackmin stack top element, the current to the stack element is added to the stackmin at the same time, when the stack element is currently going to >stackmin the top element, the stackmin stack of the current stackmin stack top element is pressed again ;
Both of these scenarios need to be synchronized with the Stackdata stack, except that only small values are saved in the first scenario Stackmin stack, and in the case of POPs, the second scenario is to be fully synchronized at the time of the pop. The code is as follows:
public class Getminstack {stack<integer> stackdata = new stack<integer> ();    stack<integer> stackmin = new stack<integer> ();            public void push (int node) {if (Stackmin.empty ()) {Stackdata.push (node);        Stackmin.push (node);            }else{//first option if (Node > Stackmin.peek ()) {Stackdata.push (node);                }else{Stackdata.push (node);            Stackmin.push (node);            }/* The second scheme int mintop = Stackmin.peek ();                if (Node > mintop) {stackdata.push (node);            Stackmin.push (Mintop);                }else{Stackdata.push (node);            Stackmin.push (node);            } */}} public void Pop () {if (!stackdata.empty () &&! stackmin.empty ()) {            int datatop = Stackdata.peek ();            int mintop = Stackmin.peek (); The first scenario if (DATatop = = mintop) {//At this time two stacks need to be out of the stack operation Stackdata.pop ();            Stackmin.pop ();            }else if (Datatop > Mintop) {stackdata.pop ();            }/* * The second scenario stackdata.pop ();            Stackmin.pop ();    */}} public int top () {return Stackdata.peek ();    } public int min () {return Stackmin.peek (); }}

2, with two stacks to achieve the function of the queue with two stacks to achieve queue, out of the function. Defines two stacks of stackpush and stackpoll,stackpush stacks used to put the elements in the queue, and the Stackpoll stack is used to get out of the queue.when entering the team, the elements are pressed into the Stackpush, the Stackpush stack elements are all imported (pop operation, because to empty the Stackpush stack) to the Stackpoll stack, the stackpoll stack pops up the top element of the stack, Then import all the elements in the Stackpoll stack (also the pop operation, because you want to empty the Stackpoll stack) into the Stackpush stack。
(the key above is thatTwo stacks import data each other to import, all imported, the other stack is emptied, otherwise it will not conform to the nature of the queue)
Look at a topic:

Write a class that can only implement queues with two stack structures, supporting the basic operation of the queue (Push,pop).

Given an action sequence ope and its length n, where the element is positive for the push operation, 0 for the pop operation, to ensure that the operation sequence is valid and must contain a pop operation, please return the result sequence of the pop.

Test examples:
[1,2,3,0,4,0],6
return: [+]
The code is as follows:
public class Twostack {public    int[] Twostack (int[] ope, int n) {        if (ope = = NULL | | n = = 0)            return null;        stack<integer> Stackpush = new stack<integer> ();        stack<integer> stackpoll = new stack<integer> ();        int popcount = 0;//The number of stacks for        (int i = 0; i < n; i++) {            if (ope[i]! = 0) {                stackpush.push (ope[i]);            } else{                popcount++;            }        }        Int[] result = new Int[popcount];        Import all data from the Stackpush stack into the stackpoll stack        while (!stackpush.empty ()) {            Stackpoll.push (Stackpush.pop ());        }        for (int i = 0; i < Popcount; i++) {            Result[i] = Stackpoll.pop ();        }        return result;}    }

3, reverse the elements in the stack to reverse the stack of elements, we first have to recursively get to the bottom of the stack, the bottom of the stack element, and then add it into the next step. So there are two steps: Get the Stack-bottom element and invert the add element. The code is as follows:
public class Stackreverse {//reverse stack public static int[] Reversestack (int[] A, int n) {if (a = = NULL | | n = = 0)        return null;        stack<integer> stack = new stack<integer> ();        for (int i = 0; i < n; i++) {Stack.push (a[i]);        } reverse (stack);//Start reverse operation for (int i = n-1; I >= 0; i--) {A[i] = Stack.pop ();    } return A; }/** * Reverse the elements in the stack * @param stack */public static void reverse (stack<integer> stack) {if (Stac        K.isempty ()) {return;        }//The following is the first recursive to get the bottom element, and then the stack of elements into the stack, the stack of elements in the order of reversal int bottom = Popbottom (stack);        reverse (stack);    Stack.push (bottom); }/** * Removes the stack bottom element and returns * @return */public static int popbottom (stack<integer> stack) {int ResU        lt = Stack.pop ();        if (Stack.isempty ()) {//pops up a stack-top element, the stack is empty, indicating that the element is the stack-bottom element return result;      }else{int last = Popbottom (stack);      Stack.push (result);//NOTE!!!        This is to put the elements in front of the pressure, so that the stack bottom element will not be pressed into the stack again return last;        }} public static void Main (string[] args) {int[] a = {9,8,7,6,5,4,3,2,1};    Reversestack (a,a.length); }}

4. Sort the elements in the stack Write a program that sorts the stack in ascending order (that is, the largest element is at the top of the stack), requiring only one additional stack to hold temporary data, but not copying elements into other data structures.
Ideas:assuming that the stack stack is the original data, and then define a secondary stack help, first remove the stack top element pops from the stack stack, the pop and help in the stack top element comparison, if the pop <= help stack top element, the pop is pressed into the help stack; > Help stack top element, remove the top element of the help stack, and put it into the stack stack until it is empty or the pop <= the top element of the stack. The code is as follows:    
public static arraylist<integer> Twostackssort (int[] numbers) {if (numbers = = null) return null;        stack<integer> stack = new stack<integer> ();        for (int i = numbers.length-1; I >= 0; i--) {Stack.push (numbers[i]);        } stack<integer> Help = new stack<integer> ();        int pop,temp;            while (!stack.isempty ()) {pop = Stack.pop ();            if (Help.isempty ()) {Help.push (POP);                }else{if (pop <= help.peek ()) {Help.push (POP);                        }else{while (!help.isempty () && pop > Help.peek ()) {//Put elements of help into the stack                        temp = Help.pop ();                    Stack.push (temp);                The//help stack is empty or the element Help.push (pop) of the top of the pop<=help stack is found; }}} while (!help.isempty ()) {Stack.push (Help.pop ());       } arraylist<integer> res = new arraylist<integer> ();        while (!stack.isempty ()) {Res.add (Stack.pop ());    } return res; }
Of course, you can also use an array as a stack to use, the array is labeled 0 as the top of the stack, the code is as follows:
/** * Array as the stack, 0 of the position is the top of the stack * @param numbers * @return * */public static arraylist<integer> TwoStacksSort2 (int[] numbers)        {if (numbers = = null) return null;        int[] help = new Int[numbers.length];        int i = 0;//point to numbers stack top element int j = -1;//point to help stack top element int pop;            while (i >= 0 && i! = numbers.length) {pop = numbers[i];            if (J < 0) {help[++j] = Pop;                }else{if (pop <= help[j]) {help[++j] = Pop;                    }else{while (J >= 0 && pop > help[j]) {numbers[i--] = help[j--];                } Help[++j] = Pop;        }} i++;        } arraylist<integer> res = new arraylist<integer> ();            for (int k = 0; k < help.length; k++) {Res.add (help[k]);        System.out.println (Help[k]);     }   return res; }

5, sliding window problems

There is an integer array of arr and a window of size w that slides from the leftmost edge of the array to the far right, and the window slides one position at a time to the right. Returns an array of length n-w+1 res,res[i] represents the maximum value for each window state. Take an array of [4,3,5,4,3,3,6,7],w=3] for example. Because the first window [4,3,5] has a maximum value of 5, the second window [3,5,4] has a maximum value of 5, and the third window [5,4,3] has a maximum value of 5. The fourth window [4,3,3] has a maximum value of 4. The fifth window [3,3,6] has a maximum value of 6. The sixth window [3,6,7] has a maximum value of 7. So the final return [5,5,5,4,6,7].

Given a shaped array of arr and its size n, given W, return an array of res. Ensure that W is less than or equal to n, and that the array size is less than or equal to 500.

Test examples:
[4,3,5,4,3,3,6,7],8,3
return: [5,5,5,4,6,7]
Ideas:The core is to define a double-ended queue Qmax, which maintains a W-data window, which holds the array's subscript, which is ejected and inserted at the team head and end of the queue, makingThe team head element is the array element referred to in the subscript, and the value in this window is maximum。 For an array of arr, when traversing to element I of an array,
Insert rule at the end of the team: the queue is definitely inserted for NULL;queue is not empty if the tail element is an array element referred to as subscriptArr[qmax.peeklast] > Current traversal element arr[i], directly insert subscript I into the tail of the team; (because although the current element Arr[i] is smaller, but when the team header element expires, it may become the maximum value of another window, so it needs to be added); If the tail element is the array element that the subscript refers toArr[qmax.peeklast] <= current traversal element Arr[i], indicating that the current team tail element subscript is not likely to be the maximum value of the back window, so the team tail element is ejected directly, and then continue to compare the new team tail elements of the index group element and the current element arr[i], according to the above rules to join;
In the team header execution Popup rule: If the team head element = = I-w, indicating that the team head element has expired, beyond the scope of the W window, the team head element directly ejected;
Process such as:

If the queue satisfies the maintenance of W elements (of course, there is not necessarily a W element value in the queue, because the queue maintains the maximum on the team head), you can directly get the array element value referred to by the tail element, which is the maximum value of the current window. The code is as follows:    
public static int[] Slide (int[] arr, int n, int w) {        if (arr = = NULL | | W < 1 | | n < w) {            return null;        }        int[] res = new INT[N-W + 1];        A double-ended queue that maintains a W window, keeping the value of the top-down element at the maximum        linkedlist<integer> Qmax = new linkedlist<integer> ();        int index = 0;        for (int i = 0; i < n; i++) {            //Execution Team tail entry rule while            (!qmax.isempty () && arr[qmax.peeklast ()] <= arr[i]) {
   qmax.polllast ();            }            Qmax.addlast (i);//Add subscript to the end of the team            //execute the header popup rule            if (qmax.peekfirst () = = i-w) {                qmax.pollfirst ();            }            if (i >= w-1) {//If at least w data is maintained in the double-ended queue, the maximum value can be obtained from the opponent at a time                res[index++] = Arr[qmax.peekfirst ()];}        }        return res;    }
The array subscript value goes up to Qmax once at a time, Qmax once, so the entire array element enters and exits the queue with an O (n) complexity, and the entire algorithm is O (n).

The next article in this series will be a list-related algorithmic question.




"Common Algorithm Thinking Analysis series" stack and queue high-frequency problem sets (modified version)

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.