Programmer code interview guide (written by Zuo Chengyun) learn ing to punch in

Posted by squariegoes on Mon, 17 Jan 2022 20:15:03 +0100

catalogue

Chapter 1 stack and queue

CD5 design the stack of getMin function

describe

Realize a stack with special functions, and then realize the operation of returning the smallest element in the stack on the basis of realizing the basic functions of the stack.

Enter Description:

In the first line, enter an integer N, which represents the total number of operations on the stack.

In the following N lines, enter a string S for each line to indicate the type of operation.

If S is "push", there is an integer X after it, indicating that the integer X is pushed into the stack.

If S is "pop", it means pop-up stack top operation.

If S is "getMin", it means asking about the minimum element in the current stack.

Output Description:

For each getMin operation, a line is output indicating the minimum element in the current stack.

Example 1

Input:

6
push 3
push 2
push 1
getMin
pop
getMin

Output:

1
2

remarks:

1<=N<=1000000

-1000000<=X<=1000000

The data guarantees that there are no illegal operations

answer

import java.util.Scanner;
import java.util.Stack;

public class Main
{
    public static class MyStack1
    {
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack1()
        {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }

        public void push(int newNum)
        {
            if (this.stackMin.isEmpty())
            {
                this.stackMin.push(newNum);
            }
            else if (newNum <= this.getMin())
            {
                this.stackMin.push(newNum);
            }
            this.stackData.push(newNum);
        }

        public int getMin()
        {
            if (this.stackMin.isEmpty())
            {
                throw new RuntimeException("Your stack is empty.");
            }
            return this.stackMin.peek();
        }

        public int pop()
        {
            if (this.stackData.isEmpty())
            {
                throw new RuntimeException("Your stack is empty.");
            }
            int value = this.stackData.pop();
            if (value == this.getMin())
            {
                this.stackMin.pop();
            }
            return value;
        }

    }

    public static class MyStack2
    {
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack2()
        {
            this.stackData = new Stack<Integer>();
            this.stackMin = new Stack<Integer>();
        }
        public void push(int newNum)
        {
            if (stackMin.isEmpty())
            {
                this.stackMin.push(newNum);
            }
            else if (newNum <= this.getMin())
            {
                this.stackMin.push(newNum);
            }
            else
            {
                int newMin = this.stackMin.peek();
                this.stackMin.push(newMin);
            }
            this.stackData.push(newNum);
        }

        public int getMin()
        {
            if (this.stackData.isEmpty())
            {
                throw new RuntimeException("Your stack is empty");
            }
            return this.stackMin.peek();
        }

        public int pop()
        {
            if (this.stackData.isEmpty())
            {
                throw new RuntimeException("Your stack is empty");
            }
            this.stackMin.pop();
            return this.stackData.pop();
        }
    }
    public static void main(String[] args)
    {
        /*
        MyStack1 myStack1 = new MyStack1();
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        for (int i = 1; i <= n; i++)
        {
            String[] inputData = scanner.nextLine().split(" ");
            if (inputData[0].equals("push"))
            {
                myStack1.push(Integer.parseInt(inputData[1]));
            }
            else if (inputData[0].equals("pop"))
            {
                myStack1.pop();
            }
            else if (inputData[0].equals("getMin"))
            {
                System.out.println(myStack1.getMin());
            }
        }
        scanner.close();
        */
        MyStack2 myStack2 = new MyStack2();
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        for (int i = 1; i <= n; i++)
        {
            String[] inputData = scanner.nextLine().split(" ");
            if (inputData[0].equals("push"))
            {
                myStack2.push(Integer.parseInt(inputData[1]));
            }
            else if (inputData[0].equals("pop"))
            {
                myStack2.pop();
            }
            else if (inputData[0].equals("getMin"))
            {
                System.out.println(myStack2.getMin());
            }
        }
        scanner.close();

    }
}

CD7 uses recursive functions and stack reverse order to create a stack

describe

Press 1,2,3,4,5 into a stack in turn, and the stack top to bottom will be 5,4,3,2,1 respectively. After the stack is transposed, it is 1,2,3,4,5 from the top to the bottom of the stack, that is, the reverse order of the elements in the stack can be realized, but it can only be realized by recursive functions, not other data structures.

Enter Description:

An integer in the first row of input data. N is the number of elements in the stack.

The next line contains N integers X_iX**i represents each element pushed in by a stack in turn.

Output Description:

The output line represents each element from the top of the stack to the bottom of the stack after the elements in the stack are in reverse order

Example 1

Input:

5
1 2 3 4 5

Output:

1 2 3 4 5

answer

import java.util.Scanner;
import java.util.Stack;

public class Main
{
    //  Recursive function 1: return and remove the elements at the bottom of the stack
    public static int getAndRemoveLastElement(Stack<Integer> stack)
    {
        // The recording position is convenient for recursion
        int x = stack.pop();
        if (stack.isEmpty())
        {
            return x;
        }
        else
        {
            int last = getAndRemoveLastElement(stack);
            stack.push(x); // Restore the original order
            return last;
        }
    }
    public static void reverse(Stack<Integer> stack)
    {
        if (stack.isEmpty())
        {
            return ;
        }
        int x = getAndRemoveLastElement(stack);
        reverse(stack);
        stack.push(x);
    }

    
    public static void main(String[] args)
    {
        Stack<Integer> stack = new Stack<>();
        Scanner scanner = new Scanner(System.in);
        int n = Integer.parseInt(scanner.nextLine());
        for (int i = 1; i <= n; i++)
        {
            int x = scanner.nextInt();
            stack.push(x);
        }
        reverse(stack);
        while (!stack.isEmpty())
        {
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
    }
}

CD13 uses one stack to sort another stack

describe

The type of elements in a stack is integer. Now if you want to sort the stack from top to bottom in order from large to small, you can only apply for one stack. In addition, you can apply for new variables, but you can't apply for additional data structures. How to finish sorting?

Enter Description:

In the first line, enter an N to indicate the number of elements in the stack

On the second line, enter N integers a_ia**i represents each element from the top of the stack to the bottom of the stack

Output Description:

The output line represents each element from the top of the stack to the bottom of the stack after sorting.

Example 1

Input:

5
5 8 4 3 6

Output:

8 6 5 4 3

remarks:

1 <= N <= 10000
-1000000 <= a_nan <= 1000000

code

import java.util.Scanner;
import java.util.Stack;

public class Main
{
    // The stack to be sorted is stack and the auxiliary stack is help. Pop the stack and record the pop-up elements as cur
    // It is discussed in two cases: 1. If cur < = help stack top element, press cur directly into the help stack
    //                  2. Cur > help stack top element stack Push (help. Pop()) until cur < = help stack top element position, and finally press cur into help
    public static void sortStackByStack(Stack<Integer> stack)
    {
        Stack<Integer> help = new Stack<>();
        while (!stack.isEmpty())
        {
            int cur = stack.pop();
            while (!help.isEmpty() && cur > help.peek())
            {
                stack.push(help.pop());
            }
            help.push(cur);
        }

        while (!help.isEmpty())
        {
            stack.push(help.pop());
        }
    }

    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        Stack<Integer> stack = new Stack<>();
        int n = Integer.valueOf(scanner.nextLine());
        // Read in data to be sorted
        for (int i = 0; i < n; i++)
        {
            int x = scanner.nextInt();
            stack.push(x);
        }
        sortStackByStack(stack);
        // Output the ordered results in the Stack
        while (!stack.isEmpty())
        {
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
    }
}

CD15 generate window maximum value array

describe

An integer array arr and a window of size w slide from the leftmost to the rightmost of the array. The window slides to the right one position at a time to find the maximum value under each window state. (if the array length is n and the window size is w, the maximum value of n-w+1 windows will be generated.)

Enter Description:

On the first line, enter n and w, representing the array length and window size, respectively

On the second line, enter n integers X_iX**i represents each element in the array

Output Description:

Output an array res with a length of n-w+1. res[i] represents the maximum value in each window state

Example 1

Input:

8 3
4 3 5 4 3 3 6 7

Output:

5 5 5 4 6 7

explain:

For example, the array is[4,3,5,4,3,3,6,7],When the window size is 3:

[4 3 5] 4 3 3 6 7        The maximum value in the window is 5

4 [3 5 4] 3 3 6 7        The maximum value in the window is 5

4 3 [5 4 3] 3 6 7        The maximum value in the window is 5

4 3 5 [4 3 3] 6 7        The maximum value in the window is 4

4 3 5 4 [3 3 6] 7        The maximum value in the window is 6

4 3 5 4 3 [3 6 7]        The maximum value in the window is 7

The output result is{5 5 5 4 6 7}

remarks:

1\le w \le n \le 10000001≤w≤n≤1000000
-1000000 \le X_i \le 1000000−1000000≤Xi≤1000000

answer

import java.util.LinkedList;
import java.util.Scanner;

public class Main
{
    public static int[] getMaxWindow(int[] arr, int w)
    {
        // Check whether the parameters are valid
        if (arr == null && w < 1 && arr.length < w)
        {
            return null;
        }
        LinkedList<Integer> qmax = new LinkedList<>();
        int[] res = new int[arr.length - w + 1];
        int index = 0;
        for (int i = 0; i < arr.length; i++)
        {
            while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[i] )
            {
                qmax.pollLast();
            }
            qmax.addLast(i);
            // {0, 1,} 2, 3, 4... w = 2
            // When i = 2, 0 is out of the team, that is, I - w = = Qmax Peekfirst() team first element out of the team
            // When qmax is about to overflow, the first element of the queue is out of the queue
            if (qmax.peekFirst() == i - w)
            {
                qmax.pollFirst();
            }
            if (i >= w - 1)
            {
                // After retrieving at least w elements, the corresponding value of the subscript of the first element of the queue can be put into the res array
                res[index++] = arr[qmax.peekFirst()];
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] inputData = scanner.nextLine().split(" ");
        int len = Integer.parseInt(inputData[0]);
        int w = Integer.parseInt(inputData[1]);
        int[] arr = new int[len];
        int[] res = new int[len - w + 1];
        int i = 0;
        for (i = 0; i < len; i++)
        {
            int x = scanner.nextInt();
            arr[i] = x;
        }
        res = getMaxWindow(arr, w);
        for (i = 0; i < res.length; i++)
        {
            System.out.print(res[i] + " ");
        }
        System.out.println();
    }
}

Topics: Algorithm data structure Interview