2021-10-29 sword finger offer (queue & stack)

JZ9 implements queues with two stacks

Title address
describe
Two stacks are used to implement a queue, and n elements are used to complete the functions of inserting integers (push) at the end of the queue n times and deleting integers (pop) at the head of the queue n times. The element in the queue is of type int. Ensure that the operation is legal, that is, ensure that there are elements in the queue during pop operation.

Data range: n ≤ 1000
Requirements: the space complexity of storing n elements is O(n), and the time complexity of insertion and deletion is O(1)
Example 1

Input:
["PSH1","PSH2","POP","POP"]
Return value:
1,2
 explain:
"PSH1":Represents inserting 1 at the end of the queue
"PSH2":Represents inserting 2 at the end of the queue
"POP":Represents deleting an element, first in first out=>Return 1
"POP":Represents deleting an element, first in first out=>Return 2 

Example 2

Input:
["PSH2","POP","PSH1","POP"]
Return value:
2,1

thinking
Define two stacks, stack1 (entry stack) and stack2 (exit stack), to complete push and pop operations.
Push: directly call the push function of stack1
Pop: first judge whether stack2 is empty. If not, directly call the pop function of stack2; If it is empty, first press all the contents of stack1 into stack2, and then call the pop function of stack2.
As shown in the following figure, for example, perform the following operations:
PUSH(1),PUSH(2),POP(),PUSH(3),PUSH(4),POP(),POP(),POP().


code

import java.util.Stack;
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();//Entry stack
    Stack<Integer> stack2 = new Stack<Integer>();//Exit stack
    public void push(int node) {
        stack1.add(node);
    }
    public int pop() {
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.add(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

JZ30 stack containing min function

Title address
describe
To define the data structure of the stack, please implement a min function in this type that can get the smallest element in the stack, and the time complexity of calling min function, push function and pop function is O(1)
push(value): push value into the stack
pop(): pop up stack top element
top(): get stack top element
min(): get the smallest element in the stack

Example:
Input: [PSH-1 "," PSH2 "," MIN "," TOP "," POP "," PSH1 "," TOP "," MIN "]
Output: - 1,2,1, - 1
Resolution:
"PSH-1" means to push - 1 into the stack, and the element in the stack is - 1
"PSH2" means to push 2 into the stack, and the elements in the stack are 2, - 1
"MIN" means to get the smallest element in the stack = = > Return - 1
"TOP" means to get the stack TOP element = = > return 2
"POP" means POP the top element of the stack, POP 2, and the element in the stack is - 1
"PSH-1" means to push 1 into the stack, and the elements in the stack are 1, - 1
"TOP" means to get the stack TOP element = = > Return 1
"MIN" means to get the smallest element in the stack = = > Return - 1

Example 1

Input:
 ["PSH-1","PSH2","MIN","TOP","POP","PSH1","TOP","MIN"]
Return value:
-1,2,1,-1

thinking
Define a stack and an additional stack minStack (i.e. the smallest stack) to record the smallest element in the current stack.
PUSH:
If you perform a push operation on the element nowVal:
1. Execute stack.push(nowVal) first
2. As follows

  • If the stack is empty (i.e. adding elements for the first time), minStack.push(nowVal)
  • If the stack is not empty: if nowval < stack top element, minStack.push(nowVal); Otherwise, minstack.push (stack top element).

POP: stack and minStack perform POP operations respectively
TOP: stack executes peek() function
MIN: minStack executes peek() function

code

import java.util.Stack;
public class Solution {
    Stack<Integer> stack=new Stack<Integer>();
    Stack<Integer> minStack=new Stack<Integer>();
    public void push(int node) {
        stack.push(node);
        if(minStack.isEmpty()||minStack.peek()>node){
            minStack.push(node);
        }else{
            minStack.push(minStack.peek());
        }
    }
    
    public void pop() {
        stack.pop();
        minStack.pop();
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int min() {
        return minStack.peek();
    }
}

Push in and pop-up sequence of JZ31 stack

Title address
describe
Enter two integer sequences. The first sequence represents the push in order of the stack. Please judge whether the second sequence may be the pop-up order of the stack. Assume that all the numbers pushed into the stack are not equal. For example, sequence 1,2,3,4,5 is the pressing sequence of a stack, and sequence 4,5,3,2,1 is a pop-up sequence corresponding to the pressing sequence, but 4,3,5,1,2 cannot be the pop-up sequence of the pressing sequence. (Note: the length of the two sequences is equal)
Example 1

Input:
[1,2,3,4,5],[4,3,5,1,2]
Return value:
false

code
Simulation method
Because the values before pop-up will be put into the stack first, the stack is used to assist.

  1. Initialization: point to the first position of pushV with pointer i, and point to the first position of popV with pointer j
  2. If pushV[i]= POPV [J], then pushV[i] should be put on the stack, + I
  3. Otherwise, pushV[i]==popV[j], indicating that this element is put into the stack and pops up immediately, so, + + I,
    ++j. Then you should check whether popV[j] is equal to the stack top element. If it is equal, + J, and pop up the stack top element
  4. Repeat 2 and 3. If i==pushV.size(), the stack sequence has been accessed. At this time, check whether the stack is empty. If it is empty, it indicates a match; Otherwise, it does not match.
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        Stack<Integer> stack=new Stack<>();
        int i=0,j=0;
        while(i<pushA.length){
            if(pushA[i]!=popA[j]){
                stack.push(pushA[i++]);
            }else{
                i++;
                j++;
                while(!stack.isEmpty()&&j<popA.length&&stack.peek()==popA[j]){
                    j++;
                    stack.pop();
                }
            }
        }
        if(stack.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
}

JZ73 flip word sequence

Title address
describe
Fish, a new employee of Niuke recently, always takes an English magazine and writes some sentences in the book every morning. Cat, a colleague, was very interested in the content written by fish. One day he borrowed it from fish, but he couldn't understand its meaning. For example, "nowcoder. a am I". Later, I realized that this guy had reversed the order of sentences and words. The correct sentence should be "I am a nowcoder.". Cat is not good at reversing the order of these words one by one. Can you help him?

Data range: 1 ≤ n ≤ 100
Advanced: space complexity 0(n) and time complexity 0(n). It is guaranteed that there is no string containing only spaces
Example 1

Input:
"nowcoder. a am I"
Return value:
"I am a nowcoder."

Example 2

Input:
""
Return value:
""

code
First, divide the string into words according to the spaces, and then flip it with the stack.

import java.util.*;
public class Solution {
    public String ReverseSentence(String str) {
        String[] strs=str.split(" ");
        Stack<String> stack=new Stack<>();
        for(int i=0;i<strs.length;i++){
            stack.push(strs[i]);
        }
        String res="";
        while(!stack.isEmpty()){
            res+=stack.pop();
            if(!stack.isEmpty()){
                res+=" ";
            }
        }
        return res;
    }
}

JZ59 maximum value of sliding window

Title address
describe
Given an array num of length n and the size of the sliding window, find the maximum value in all sliding windows.

For example, if you enter the array {2,3,4,2,6,2,5,1} and the size 3 of the sliding window, there are six sliding windows, and their maximum values are {4,4,6,6,5}; There are six sliding windows for the array {2,3,4,2,6,2,5,1}: {[2,3,4], 2,6,2,5,1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2,5,1}, {2,3,4, [2,6,2], 5,1}, {2,3,4,2, [6,5], 1}, {2,3,4,2,6, [2,5,1]}.

When the window is longer than the array length or the window length is 0, null is returned.

Data range: 1 ≤ n ≤ 10000, 0 ≤ size ≤ 10000. The value of each element in the array meets ∣ val ∣ ≤ 10000
Requirements: space complexity O(n), time complexity O(n)

Example 1

Input:
[2,3,4,2,6,2,5,1],3
 Return value:
[4,4,6,6,6,5]

Example 2

Input:
[9,10,9,-7,-3,8,2,-6],5
 Return value:
[10,10,9,8]

Example 3

Input:
[1,2,3,4],5
 Return value:
[]

Problem solving ideas
Prepare a double ended queue qmax, maintain the descending order from the head of the team to the tail of the team, add elements from the tail of the team, and take elements from the head of the team.

  1. Traverse each element of the array
  2. If the container is empty, the current element is directly added to the container.
  3. If the container is not empty, compare the current element with the last element of the container. If it is greater than, delete the last element of the container, and then continue to compare the current element with the last element of the container
  4. If the current element is smaller than the last element of the container, the current element is added directly to the end of the container
  5. If the element of the container header no longer belongs to the boundary of the current window, the header element should be deleted
    Examples are as follows:
    For the array {2,3,4,2,6,2,5,1}, the window size is 3. Then there are six sliding windows, and their maximum values are {4,4,6,6,5}; There are six sliding windows for the array {2,3,4,2,6,2,5,1}: {[2,3,4], 2,6,2,5,1}, {2, [3,4,2], 6,2,5,1}, {2,3, [4,2,6], 2,5,1}, {2,3,4, [2,6,2], 5,1}, {2,3,4,2, [6,5], 1}, {2,3,4,2,6, [2,5,1]}.
    According to the algorithm, the execution is as follows:








code

import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
        ArrayList<Integer> res=new ArrayList<>();
        if(num==null||size<1||size>num.length){
            return res;
        }
        LinkedList<Integer> qmax=new LinkedList<>();
        for(int i=0;i<num.length;i++){
            while(!qmax.isEmpty()&&num[qmax.peekLast()]<=num[i]){
                qmax.pollLast();
            }
            qmax.offerLast(i);
            if(qmax.peekFirst()==i-size){
                qmax.pollFirst();
            }
            if(i>=size-1){
                res.add(num[qmax.peekFirst()]);
            }
        }
        return res;
    }
}

Tags: Java Algorithm data structure queue stack

Posted on Tue, 02 Nov 2021 11:44:29 -0400 by Alien