Swordfinger offer Title Resolution (with video resolution link)

Keywords: Java github

Write before

Code description: Code download address: https://github.com/WuNianLuoMeng/Coding
Video Description: The first time you record a video in this form, if there is anything wrong, please also point out in time, thank you~~

Finding in a two-dimensional array

Method 1:

By traversing the array, find out if there is a target in the array.Its time complexity is (O(n * m))

    public boolean Find(int target, int [][] array) {
        for (int i = 0; i < array.length; i++)
        {
            for (int j = 0; j < array[0].length; j++)
            {
                if (array[i][j] == target)
                    return true;
            }
        }
        return false;
    }

Method 2 (starting at the upper right corner of the matrix):

Set an i, J to indicate the current location you are looking for, if array[i][j] > target is large, then look left and vice versa until you find array[i][j] == target.Its time complexity is O(n + m)

public boolean Find(int target, int [][] array) {
        int i = 0;
        int j = array[0].length - 1;
        while(i >= 0 && i < array.length && j >= 0 && j < array[0].length)
        {
            // array[i][j]
            if (array[i][j] == target)
                return true;
            else if (array[i][j] > target)
                j--;
            else
                i++;
        }
        return false;
    }

Method three (starting at the lower left corner of the matrix):

Set an i, J to indicate the current location you are looking for, if array[i][j] > target is large, then look up and right until you find array[i][j] == target.Its time complexity is O(n + m)

public boolean Find(int target, int [][] array) {
        int i = array.length - 1;
        int j = 0;
        while(i >= 0 && i < array.length && j >= 0 && j < array[0].length)
        {
            // array[i][j]
            if (array[i][j] == target)
                return true;
            else if (array[i][j] > target)
                i--;
            else
                j++;
        }
        return false;
    }

Replace spaces

Method 1: Go through the string and determine if the character at the current position is a space. If it is a space, append'%20'. If it is not, append the character at the current position.

public String replaceSpace(StringBuffer str) {
        int len = str.length();
        String res = "%20";
        StringBuffer ans = new StringBuffer();
        for (int i = 0; i < len; i++) {
            ans.append(str.charAt(i) == ' ' ? res : str.charAt(i));
        }
        return ans.toString();
    }

Print chain list from end to end

Method 1: Simulate the stack process using the Stack class in Java

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        while(listNode != null) {
            stack.add(listNode.val); ///Put the current node's value on the stack
            listNode = listNode.next; ///Update the current node to be the next node
        }
        while (!stack.isEmpty()) {
            list.add(stack.pop()); ///Remove the current top stack element and place it in the list
        }
        return list;
    }

Method 2: Recursively simulate the effect of chain list inversion

private static ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        ArrayList<Integer> list = new ArrayList<>();
        if (listNode == null) {
            return list;
        }
        return solve(list, listNode);
    }
    // 1->2->3->4
    private static ArrayList<Integer> solve(ArrayList<Integer> list, ListNode listNode) {
        if (listNode.next != null) {   ///The next node of the current node is not empty
            list = solve(list, listNode.next); ///Recursion down
        }
        list.add(listNode.val);
//        System.out.println(list);
        return list;
    }

Rebuilding Binary Tree

Method 1: By traversing the preceding sequence in turn, and then determining the position of the number in the current traversed preceding sequence in the middle sequence, then dividing the left and right subtrees of the current node, and finally passing in the recursive program.

import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

public class Main4 {
    private static int index = 0;
    private static TreeNode solve(int[] pre, int[] tempIn) {
        int len1 = 0; ///Number of nodes in the left subtree of the current node
        int len2 = 0; ///Number of nodes in the right subtree of the current node
        for (int i = 0; i < tempIn.length; i++) {
            if (pre[index] == tempIn[i]) {
                break;
            }
            len1 ++; ///Number of left subtree nodes+.
        }
        len2 = tempIn.length - len1 - 1;

        int index1 = 0;
        int index2 = 0;
        int[] temp1 = new int[len1]; ///Left subtree of current node
        int[] temp2 = new int[len2]; ///Right subtree of current node
        boolean flag = false;
        for (int i = 0; i < tempIn.length; i++) {
            if (pre[index] == tempIn[i]) {
                flag = true;
            } else if (!flag) {
                temp1[index1++] = tempIn[i];
            } else {
                temp2[index2++] = tempIn[i];
            }
        }
        TreeNode node = new TreeNode(pre[index]);
        node.right = null;
        node.left = null;
//        System.out.printf("%d left subtree:", pre[index]);
//        for (int i = 0; i < temp1.length; i++) {
//            System.out.printf("%d ", temp1[i]);
//        }
//        System.out.printf(",");
//        System.out.printf ('%d right subtree:', pre[index]);
//        for (int i = 0; i < temp2.length; i++) {
//            System.out.printf("%d ", temp2[i]);
//        }
//        System.out.println();
        if (index < pre.length && temp1.length > 0) {
            index++; ///Traverse the subscript of the preceding sequence plus 1
            node.left = solve(pre, temp1); ///Create a left subtree of the current node
        }
        if (index < pre.length && temp2.length > 0) {
            index++; ///Traverse the subscript of the preceding sequence plus 1
            node.right = solve(pre, temp2); ///Create the right subtree of the current node
        }
        return node;
    }
    private static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        index = 0; ///Traverse subscript of prefix sequence
        return solve(pre, in);
    }

    public static void main(String[] args) {
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; ///Pre-traversal
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; ///Ordered traversal
        TreeNode root = reConstructBinaryTree(pre, in);

        dfs1(root);
        System.out.println();
        dfs2(root);
        System.out.println();
        dfs3(root);
        System.out.println();

    }
    private static void dfs1(TreeNode node) {
        System.out.printf("%d ", node.val);
        if (node.left != null) {
            dfs1(node.left);
        }
        if (node.right != null) {
            dfs1(node.right);
        }
    }
    private static void dfs3(TreeNode node) {
        if (node.left != null) {
            dfs3(node.left);
        }
        if (node.right != null) {
            dfs3(node.right);
        }
        System.out.printf("%d ", node.val);
    }

    private static void dfs2(TreeNode node) {
        if (node.left != null) {
            dfs2(node.left);
        }
        System.out.printf("%d ", node.val);
        if (node.right != null) {
            dfs2(node.right);
        }
    }

}

Using two stacks to implement a queue

Method 1: Queue functionality is achieved by replica exchange between elements in two stacks.

import java.util.Stack;

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

    public void push(int node) {
        while (!stack2.isEmpty()) {
            stack1.push(stack2.pop());  ///Place elements from stack 2 in stack 1
        }
        stack1.push(node);
    }

    public int pop() {
        while (!stack1.isEmpty()) {
            stack2.push(stack1.pop()); ///Place elements from stack 1 in stack 2
        }
        return stack2.pop();
    }
}

Minimum number of rotation arrays

Method 1: Traverse the array and keep updating the variable that holds the minimum value.Time complexity is O(n)

    public int minNumberInRotateArray(int [] array) {
        if (array.length == 0) {
            return 0;
        }
        int ans = array[0];
        for (int i = 1; i < array.length; i++) {
            ans = Math.min(ans, array[i]);
        }
        return ans;
    }

Method 2: The subscripts that exist in two subarrays (two non-decreasing emission reduction order subarrays) are continuously updated by the binary method.Time complexity is O(log(n))

 public int minNumberInRotateArray(int[] array) {
        if (array.length == 0) {
            return 0;
        }
        int l = 0;
        int r = array.length - 1;
        while (l < r - 1) {
            int mid = (l + r) >> 1;
            if (array[mid] >= array[l]) {
                l = mid; ///Indicates that the mid is in the first non-decreasing subarray
            } else if (array[mid] <= array[r]) {
                r = mid; ///Indicates that the mid is in the second non-decreasing subarray
            }
        }
        return array[r];
    }

Fibonacci Range

Method 1: Calculate a[n] value recursively

    public int Fibonacci(int n) {
        if (n == 0) {
            return 0;
        }
        int[] a = new int[n + 1];
        if (n == 1 || n == 2) {
            return 1;
        }
        a[1] = 1;
        a[2] = 1;
        for (int i = 3; i <= n; i++) {
            a[i] = a[i - 1] + a[i - 2];
        }
        return a[n];
    }

Method 2: Recursively find the value of a[n]

public int Fibonacci(int n) {
        if (n == 0) {
            return 0; ///Terminate recursion condition
        }
        if (n == 1 || n == 2) {
            return 1; ///Terminate recursion condition
        }
        return Fibonacci(n - 1) + Fibonacci(n -2);
    }

Step Jump

Method 1: Use a recursive method to simulate the choices made each time you jump a step: either step 1 or step 2.

 public int JumpFloor(int target) {
        if (target == 1) {
            return 1; ///Now recursive to step 1, there is no need to go down recursive
        }
        if (target == 2) {
            return 1 + JumpFloor(target - 1); ///If target == 2, it is actually equal to the total number of jumps in the case of jumping directly from the starting position to the first order + recursion
//            return 2;
        }
        return JumpFloor(target - 1) + JumpFloor(target - 2); ///The current number of target steps is equal to 1 step forward plus 2 steps forward
    }

Method 2: Recursively calculates the equation between the total number of cases from the starting point to the first order and the total number of cases from the starting point to the first order and the total number of cases from the starting point to the second order.

public int JumpFloor(int target) {
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int[] a = new int[target + 1]; /// a[i] represents the total number of cases from start to order I I
        a[1] = 1; ///The total number of first-order cases is 1
        a[2] = 2; ///The total number of second-order cases is 2
        for (int i = 3; i <= target; i++) {
            a[i] = a[i - 1] + a[i - 2]; ///The total number of cases for the first order is equal to the number of cases from the starting point to the I-1 order (from 0 -> i-1 -> +1 = i) plus the number of cases from the starting point to the i-2 order (0 -> i-2 -> +2 -> i)
        }
        return a[target];
    }

Metamorphic Step Jump

Method 1: Recursively, for the total number of jumps on step I i, he is equal to the sum of cases from the first to the i-1, and then adds the number of cases from the beginning to the end.

public int JumpFloorII(int target) {
        if (target == 1) {
            return 1;
        }
        int[] a = new int[target + 1];
        int sum = 1; ///Set a sum variable to record the total number of cases in order 1 to n-1
        for (int i = 2; i <= target; i++) {
            a[i] = sum + 1; ///For step I he is equal to the sum of the cases from step 1 to step i-1 and then adds 1 (from start to step i)
            sum = sum + a[i]; ///Number of cases that need to be updated in order 1 to i I
        }
        return a[target];
    }

Matrix Coverage

Method 1: For a 2i rectangle, his case number is equal to 2(i-1) on the basis of a vertical 21 small matrix on the right side, and then add 2(i-2) rectangle on the basis of two 2*1 small matrices across the right side.

public int RectCover(int target) {
        if (target == 0) {
            return 0;
        }
        if (target == 1) {
            return 1;
        }
        if (target == 2) {
            return 2;
        }
        int[] a = new int[target + 1];
        a[1] = 1;
        a[2] = 2;
        for (int i = 3; i <= target; i++) {
            a[i] = a[i - 1] + a[i - 2];  ///For a 2*i rectangle, his case number is 2*(i-1) based on a vertical 2*1 small matrix on the right, then 2*(i-2) based on a rectangle and two 2*1 small matrices across the right.
        }
        return a[target];
    }

Number of 1 in binary

Method 1: Essentially, every bit in the binary representation of n is judged.

eg:
5-"101 & 1 -" 10 & 1 - "1 & 1 -" 0 & 1 This method is problematic.
1 -> 0000000...01 -> (-1) -> 11...11111 ->Move 1 bit to the right, the left of the binary of number-1 is complemented by 1, that is, no matter how many times you move right, the result will be -1.

Improvement: Operate on the number following the n&operation:
5-> 101 & 1 -> 101 & 10 -> 101 & 100

    public int NumberOf1(int n) {
        int sum = 0; ///Number of record 1
        int temp = 1; ///is essentially a temp variable to determine if each digit of n is 1
        while (temp != 0) { ///When temp is 0, it means that 32 times have been moved, and then it means that each of n has been traversed
            sum = (n & temp) != 0 ? sum + 1 : sum;
            temp = temp << 1;
        }
        return sum;
    }

Method 2: Essentially, the position of 1 in the binary representation of n is determined.

eg:
5 -> 101 & 100(101 - 1) = 100 -> 100 & 011(100 - 1) = 000 -> 000

public int NumberOf1(int n) {
        int sum = 0; ///Number of record 1
        while (n != 0) {  ///Indicates that there must be 1 in the binary representation of the current n
            sum++;
            n = n & (n - 1); ///Essentially, it eliminates 1 at the first position from right to left.
        }
        return sum;
    }
43 original articles published, 7 praised, 8299 visits
Private letter follow

Posted by marcela1637 on Tue, 28 Jan 2020 20:34:48 -0800