(The latest version 2022 version) Sword refers to the offer queue & stack solution


1. "Jianzhi offer" JZ9 implements queues with two stacks

Title description:

Use two stacks to implement a queue, and use n elements to complete the function of inserting an integer (push) at the end of the queue n times and deleting an integer (pop) at the head of the queue n times. The elements in the queue are of type int. Ensure that the operation is legal, that is, ensure that there are elements in the queue when the pop operation is performed.

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

Problem-solving ideas:

Let's first analyze the queue and stack operations by matching the bottom of the stack with the head of the team, and the top of the stack with the tail of the team. In this case, entering the team can be regarded as pushing into the stack, and the difficulty lies in getting out of the team.

The result of the dequeue operation is to take out the first element at the head of the queue, which corresponds to taking out the bottom element of the stack. To take out the bottom element of the stack, other elements must first be popped out of the stack, and the elements after popping are pushed into another stack, and the bottom element of the stack is taken out, and then these elements are put back.

Programmatic implementation (Java):

import java.util.Stack;

public class Solution {
    
    
    //入栈只对stack1操作,出栈只对stack2操作
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
    
    
        stack1.push(node);
    }

    public int pop() {
    
    
        //栈2不为空直接pop元素
        if (!stack2.isEmpty()) {
    
    
            return stack2.pop();
            //栈2空,栈1不空,把栈1中所有元素装入栈2
        } else if (!stack1.isEmpty() && stack2.isEmpty()) {
    
    
            while (!stack1.isEmpty()) {
    
    
                stack2.push(stack1.pop());
            }
            return stack2.pop();
            //栈1,栈2都为空,返回-1。
        } else {
    
    
            return -1;
        }
    }
}

2. "Jianzhi offer" JZ30 contains a stack of min functions

Title description:
Define the data structure of the stack. Please implement a min function in this type that can get the smallest element contained in the stack. When inputting operations, ensure that there must be elements in the stack when the pop, top, and min functions operate.

The methods contained in this stack are:
push(value): push value into the stack
pop(): pop the top element of the stack
top(): get the top element of the stack
min(): get the smallest element in the stack

Data range: the number of operations satisfies 0 \le n \le 300 \0≤n≤300, and the input elements satisfy |val| \le 10000 \∣val∣≤10000
Advanced: The time complexity of each operation of the stack is O( 1)\O(1), the space complexity is O(n)\O(n)

Problem-solving idea:
The time complexity is required to be O(1), and the stack operation time of stacking and popping is also O(1), that is to say, it is necessary to store the maximum and minimum values ​​synchronously when the data is pushed into the stack. Focus on stacking and popping. Here we define a new minvalues ​​array as the minimum stack. When an element is pushed onto the stack, if the previous stack is empty, it is obvious that this element is the minimum value. When the stack is not empty, if the current element is smaller than the value of the minimum stack, the value of this element is pushed to the minimum stack synchronously, otherwise the minimum stack (stack top element) of the minimum stack is pushed to the top of the minimum stack. The stack and the minimum stack are pushed and popped synchronously to ensure that the top element of the minimum stack is the minimum value

Programming implementation:

import java.util.Stack;

public class Solution {
    
    
    Stack<Integer> stack1 = new Stack<>();
    Stack<Integer> stack2 = new Stack<>();

    public void push(int node) {
    
    
        stack1.push(node);
        if (stack2.isEmpty() || node <= stack2.peek()) {
    
    
            stack2.push(node);
        }
    }

    public void pop() {
    
    
        //if(stack1.peek().intValue() == stack2.peek().intValue()){
    
    
        if (stack1.peek().equals(stack2.peek())) {
    
    
            stack2.pop();
        }
        stack1.pop();
    }

    public int top() {
    
    
        return stack1.peek();
    }

    public int min() {
    
    
        return stack2.peek();
    }
}

3. The maximum value of the sliding window of JZ59 in "Jianzhi offer"

Title description:

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

For example, if the input array is {2,3,4,2,6,2,5,1} and the size of the sliding window is 3, then there are 6 sliding windows in total, and their maximum values ​​are {4,4,6, 6,6,5}; There are 6 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,2,5],1}, {2,3,4,2,6,[2,5, 1]}.

When the window is larger than the length of the array or the length of the window is 0, return empty.

Data range: 1 \le n \le 100001≤n≤10000, 0 \le size \le 100000≤size≤10000, the value of each element in the array satisfies |val| \le 10000∣val∣≤10000
Requirements: complex space Degree O(n)O(n), time complexity O(n)O(n)

Problem-solving ideas:

explain:

The position of the sliding window maximum value
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7

hint:

  • You can assume that k is always valid, 1 ≤ k ≤ the size of the input array provided that the input array is not empty.

Analysis
We can use double-ended queues to maintain a monotonically non-decreasing queue to represent the current maximum value. Since the queue is monotonically non-decreasing, the element at the head of the queue is the smallest element.

Programmatic implementation (Java):

import java.util.*;
public class Solution {
    
    
    public ArrayList<Integer> maxInWindows(int [] num, int size) {
    
    
        ArrayList<Integer> list = new ArrayList<>();
        if (size > num.length || size == 0) {
    
    
            return list;
        }

        Deque<Integer> queue = new LinkedList<>();
        for (int i = 0; i < num.length; i++) {
    
    
            //num[1, 3, -1, -3, 5, 3, 6, 7]
            //下标[1, 2, 3],单调队列,保持队列递增
            while (!queue.isEmpty() && num[queue.peekLast()] < num[i]) {
    
    
                queue.pollLast();
            }

            queue.add(i);
            //如果队列中元素超过size,把最先加入的下标poll()
            if (queue.peekLast() - queue.peekFirst() >= size) {
    
    
                queue.pollFirst();
            }

            //滑动窗口向后移,并加入list中
            if (i + 1 >= size) {
    
    
                list.add(num[queue.peekFirst()]);
            }
        }
        return list;
    }
}

4. The push and pop sequence of the JZ31 stack in "Jianzhi offer"

Title description:

Input two integer sequences, the first sequence represents the push order of the stack, please judge whether the second sequence may be the pop order of the stack. Assume that all numbers pushed onto the stack are unequal. For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a certain stack, and the sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the push sequence, but 4, 3, 5, 1, 2 It cannot be the pop sequence of the push sequence.

  1. 0<=pushV.length == popV.length <=1000
  2. -1000<=pushV[i]<=1000
  3. All numbers of pushV are different

Programming implementation (Java):

import java.util.*;

public class Solution {
    
    
    public boolean IsPopOrder(int [] pushA,int [] popA) {
    
    
        if(pushA.length == 0){
    
    
            return true;
        }

        Stack<Integer> stack = new Stack<>();
        int k = 0;
        for(int i = 0; i < pushA.length; i++){
    
    
            stack.push(pushA[i]);
            while(!stack.isEmpty() && stack.peek().equals(popA[k])){
    
    
                stack.pop();
                k++;
            }
        }
        return stack.isEmpty();
    }
}

5. "Jianzhi offer" JZ73 reverses the word sequence

Title description:
Description
Niuke recently had a new employee, Fish, who would always hold an English magazine every morning and write some sentences in the notebook. Colleague Cat was very interested in what Fish wrote. One day he borrowed it from Fish to read it, but he couldn't understand its meaning. For example, "nowcoder. a am I". I realized later that the guy had reversed the order of the words in the sentence, and the correct sentence should be "I am a nowcoder." Cat is not good at flipping these words one by one, can you help him?

Data range: 1 \le n \le 100 \1≤n≤100
Advanced: space complexity O(n) \O(n), time complexity O(n) \O(n), ensure that there are no spaces String


public class Solution {
    
    
    public String ReverseSentence(String str) {
    
    
        str = str.trim();
        StringBuilder s = new StringBuilder();
        int i = str.length() - 1;
        int j = i;
        while(i >= 0){
    
    
            //找到倒数第一个空格
            while(i >= 0 && str.charAt(i) != ' ') i--;
            //将倒数第一个单词拼接到s上
            s.append(str.substring(i + 1, j + 1) + " ");
            //清除倒数第一个单词前连续多个空格
            while(i >= 0 && str.charAt(i) == ' ') i--;
            j = i;
        }
        return s.toString().trim();
    }
}

Guess you like

Origin blog.csdn.net/weixin_51405802/article/details/127611128