[Second Day of Interview Surprise Algorithm] Sword Pointer Offer + Leetcode Hot100

The Bright Sword Project was officially launched on June 25, 2022. Until the beginning of August, 5 algorithm questions will be reviewed every day. The questions I chose are Sword Pointer Offer and LeetCodeHot100, because these questions are basically common interview questions, and you can do more before the interview. Just look at the interview experience and familiarize yourself with the algorithm questions that each company has tested.

The sword points to Offer 09. Use two stacks to implement the queue

  • Question meaning: Use two stacks to implement a queue. The queue is declared as follows. Please implement its two functions appendTail and deleteHead to complete the functions of inserting an integer at the end of the queue and deleting an integer at the head of the queue respectively. (If there are no elements in the queue, the deleteHead operation returns -1)
  • Example:
    输入:
    ["CQueue","appendTail","deleteHead","deleteHead"]
    [[],[3],[],[]]
    输出:[null,null,3,-1]
    
  • Idea: One stack serves as input, and another stack serves as output, that is, the elements are first written into one stack, and then popped out of the stack and written into another stack. In this way, the characteristics can be 先进先出achieved
  • Code:
    class CQueue {
          
          
        Deque<Integer> stack1;
        Deque<Integer> stack2;
        public CQueue() {
          
          
            stack1 = new LinkedList<>();
            stack2 = new LinkedList<>();
        }   
        public void appendTail(int value) {
          
          
        	// 添加元素的时候,只需要使用输入栈
            stack1.push(value);
        }
        public int deleteHead() {
          
          
            if (stack2.isEmpty()) {
          
          // 如果不为空,那么直接出栈就行了
                while (!stack1.isEmpty()) {
          
          // 如果为空,就说明没有输入元素或者元素全部已经出栈
                    stack2.push(stack1.pop());
                }
            }
            return stack2.isEmpty() ? -1 : stack2.pop();
        }
    }
    

Sword Points to Offer 10- I. Fibonacci Sequence

  • Question meaning: Write a function, input n, and find the nth term of the Fibonacci sequence (i.e. F(N)). The Fibonacci sequence is defined as follows:
    F(0) = 0,   F(1) = 1
    F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
    
    The Fibonacci sequence starts with 0 and 1, and subsequent Fibonacci numbers are calculated by adding the previous two numbers. The answer needs to be modulo 1e9+7 (1000000007). If the initial calculation result is: 1000000008, please return 1.
  • Example:
    输入:n = 2
    输出:1
    
  • Idea: If this question is classified as a dynamic programming question, then the recursion formula is very easy to write, and the initialization part is also very easy, but what is the difficulty? That is, the answer needs to be modulo 1e9+7 , so the state needs to be modulo during the recursion process.
  • Code:
    class Solution {
          
          
        public int fib(int n) {
          
          
            if (n <= 1)
                return n;
            int[] dp = new int[n + 1];
            dp[0] = 0;
            dp[1] = 1;
            for (int i = 2; i <= n; i++) {
          
          
                dp[i] = dp[i - 1] + dp[i - 2];
                dp[i] %= 1000000007;
            }
            return dp[n];
        }
    }
    

Sword Points Offer 10- II. Frog Jumping Stairs Problem

  • Question: A frog can jump up 1 step or 2 steps at a time. Find out how many ways the frog can jump up an n-level staircase. The answer needs to be modulo 1e9+7 (1000000007). If the initial calculation result is: 1000000008, please return 1.
  • Example:
    输入:n = 2
    输出:2
    
  • Idea: 斐波那契数列Same as the recursive formula, the only difference is the initialization
  • Code:
    class Solution {
          
          
        public int numWays(int n) {
          
          
            if (n <= 1)
                return 1;
            int[] dp = new int[n + 1];  
            dp[0] = 1;
            dp[1] = 1;
            for (int i = 2; i <= n; i++) {
          
          
                dp[i] = dp[i - 1] + dp[i - 2];
                dp[i] %= 1000000007;
            }
            return dp[n];
        }
    }
    

Sword pointing to Offer 11. Minimum number of rotated array

  • Question meaning: Moving the first elements of an array to the end of the array is called rotation of the array. You are given an array numbers that may have duplicate element values. It is originally an array arranged in ascending order and rotated as described above. Please return the smallest element of the rotated array. For example, the array [3,4,5,1,2] is a rotation of [1,2,3,4,5], and the minimum value of the array is 1.
  • Example:
    输入:numbers = [3,4,5,1,2]
    输出:1
    
  • Idea: The first idea is that we observe that this rotated sequence has a characteristic, that is, there is an increasing sequence before the turning point, and there is an increasing sequence after the turning point. Then the turning point is actually the minimum point, so the minimum can be found in one traversal process. value; the second idea is that it is a semi-ordered sequence, which reminds me that binary search is difficult.
  • Code:
    class Solution {
          
          
    	public int minArray(int[] numbers) {
          
          
            int l = 0, r = numbers.length - 1;
            while (l <= r) {
          
          
                int mid = l + (r - l) / 2;
                if (numbers[mid] > numbers[r])   // 排除左边部分  
                    l = mid + 1;
                else if (numbers[mid] < numbers[r])  // 排除右边部分  但是mid可能就是最小值
                    r = mid;
                else    
                    r -= 1;      // 因为这个时候最小值有可能在mid左边,也有可能在mid右边,所以只能排除r
            }
            return numbers[l];
        }
    }
    

The sword points to Offer 12. Paths in the matrix

  • Question: Given an mxn two-dimensional character grid board and a string word word. Returns true if word exists in the grid; otherwise, returns false. Words must be formed from letters in adjacent cells in alphabetical order, where "adjacent" cells are those that are adjacent horizontally or vertically. Letters in the same cell are not allowed to be used repeatedly.
  • Example:
    输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
    输出:true
    
  • Idea: Set a template of the island area
  • Code:
    class Solution {
          
          
        public boolean exist(char[][] board, String word) {
          
          
            int m = board.length, n = board[0].length;
            boolean[][] visited = new boolean[m][n];   // 防止死循环
            // 从每一个位置进行递归搜索
            for (int i = 0; i < m; i++) {
          
          
                for (int j = 0; j < n; j++) {
          
          
                    if (dfs(board, word, visited, i, j, 0))
                        return true;
                }
            }
            return false;
        }
        
        private boolean dfs(char[][] board, String word, boolean[][] visited, int i, int j, int index) {
          
          
            int m = board.length, n = board[0].length;
            if (i < 0 || i >= m || j < 0 || j >= n || visited[i][j])
                return false;
            if (board[i][j] != word.charAt(index))
                return false;
            if (index == word.length() - 1)
                return true;
            visited[i][j] = true;
            boolean result = dfs(board, word, visited, i - 1, j, index + 1) ||
            dfs(board, word, visited, i + 1, j, index + 1) ||
            dfs(board, word, visited, i, j - 1, index + 1) ||
            dfs(board, word, visited, i, j + 1, index + 1);
            visited[i][j] = false;
            return result;
        }
    }
    

Guess you like

Origin blog.csdn.net/qq_42397330/article/details/125467045