BAT conventional algorithm, get to know

One, binary tree


1.1 Binary tree traversal by layer

  • 1. First traverse the width of the binary tree
  • 2. Breadth-first traversal often uses queue structure
  • 3. In the interview, this type of question often has some instructions on line breaks, such as printing the line number

Topic 1: Given the head node head of a binary tree, please print it in the format that everyone sees now. Request to be printed as:

  The result of traversing in layer order is the right side:

Java code implementation:

    // 层序遍历
    // 时间复杂度:O(n)
    // 空间复杂度:O(n)
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new LinkedList<>();
        if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new LinkedList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                list.add(poll.val);
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
            }
            res.add(list);
        }

        return res;
    }

1.2 Binary tree serialization and deserialization

  1. Binary Tree ——> String (Serialization)
  2. String ——> Binary Tree (deserialization)

Serialization method:

  1. Serialize according to pre-order traversal
  2. Serialize according to in-order traversal
  3. Traverse serialization according to post-order
  4. Serialize by layer

Case number one:

The process of recording the binary tree into a file is called the serialization of the binary tree, and the process of reconstructing the original binary tree from the contents of the file is called the deserialization of the binary tree. Given the head node head of a binary tree, the type of the node value of the binary tree is known to be a 32-bit integer. Please design a binary tree serialization and deserialization scheme and implement it in code.

Case one answer:

  1. Assuming that the serialization result is str, initially str is an empty string.
  2. If an empty node is encountered when traversing the binary tree first, add "#!" to the end of str.
  3. If you encounter a node that is not empty, assuming the node value is 3, add "3!" to the end of str.

Note: If you don't use special symbols to indicate the end of the value, the serialization result of the two trees is: 123###, which means that if you don't use special characters to indicate the end of the node value, ambiguity will occur.

Deserialization: How to deserialize the result of a binary tree through pre-order traversal.

  1. Choose which traversal method to serialize, and choose which method to deserialize.
  2. The result of serialization of a tree is unique, and the binary tree generated by the unique result is also unique.

Second, sort

The time complexity is O(n^2): bubble sort, selection sort, insertion sort

2.1 Bubble sort

Bubble sort algorithm idea:

  • Time complexity is O(n^2)
  • Space complexity is O(1)

Implementation code:

 


2.2 Selection sort

Selection and sorting algorithm ideas:

  • Time complexity is O(n^2)
  • Space complexity is O(1)

Implementation code:

 


2.3 Insertion sort

Insert sort algorithm idea:

  • Time complexity is O(n^2)
  • Space complexity is O(1)

Implementation code:

 


Time complexity: O(N*logN): merge sort, quick sort, heap sort, Hill sort

2.4 Merge Sort

The idea of ​​merge sort algorithm:

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Implementation code:

 


2.5 Quick sort

Quick sort algorithm ideas:

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Implementation code:

 


2.6 Heap sort

Heap sorting algorithm ideas:

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Implementation code:

 


2.7 Hill sort

Hill sorting algorithm idea: an improved version of insertion sort, continuously improving the step size. The key to Hill sorting is the choice of step size

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Implementation code:

 


The sorting algorithm with O(N) time complexity is not a sorting algorithm based on comparison. The idea comes from bucket sorting: counting sorting, cardinal sorting

2.8 Count and sort

Counting and sorting algorithm ideas:

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Applicable scenarios: data in a certain range

Implementation code:

 


2.9 Cardinality Sort

Radix sorting algorithm idea:

  • Time complexity is O(N*logN)
  • Space complexity is O(1)

Implementation code:

 


Space complexity of classic sorting algorithms

  • O(1): Insertion sort, selection sort, bubble sort, heap sort, Hill sort
  • O(logN) ~ O(N): Quick sort
  • O(N): merge sort
  • O(M): Count sorting, base sorting

Stability of Classic Sorting Algorithm

The concept of stability:

Suppose that there are multiple records with the same key in the sequence to be sorted. If sorted, the relative order of these records remains unchanged. This sorting algorithm is said to be stable, otherwise it is called unstable.

Stable sorting concept:

Bubble sort, insertion sort, merge sort, count sort, radix sort, bucket sort

Unstable sorting algorithm:

Select sort, quick sort, hill sort, heap sort


Supplementary Note 1: The sorting algorithm has no absolute advantages and disadvantages

It is usually not easy to say which sorting algorithm is good. This is related to the elements to be sorted. For example, sorting people's age or height, because this kind of data range is usually relatively small, you can consider using counting sorting. But for uniformly distributed integers, counting ordering is not appropriate. Unless specifically stated in the interview question, it is believed that the range of data to be sorted is evenly distributed.

Supplementary Note 2: Why is it called Quick Sort

The reason why quick sort is called quick sort does not mean that it is better than heap sort and merge sort. In the best case, its progressive complexity is the same as heap sort and merge sort. It's just that the constant coefficient of quick sort is relatively small.

Supplementary Note 3: Sorting in Engineering

  1. The engineering sort is a comprehensive sort.
  2. When the array is small, insert sort.
  3. When the array is large, quick sort or other O(N*logN) sorting.

Sorting case one:

An almost ordered array is known. Almost ordered means that if the array is arranged in order, the distance of each element does not exceed K, and K is small relative to the length of the array. May I ask which method is better to sort them?

Ideas:

Sorting algorithms with O(N) time complexity: counting sorting, cardinal sorting, not based on the restriction of comparison sorting algorithms, and not applicable to all situations.

Sorting algorithm with O(N^2) time complexity: bubble sorting, selection sorting. These two sorting algorithms have nothing to do with the original sequence of the array; insertion sort, the process of insertion sort is related to the original order, and the movement distance of each element does not exceed K. For this question, insertion sort O(N*K)

Sorting algorithm with time complexity of O(N*logN): quick sort, independent of the original order of the array. The merge sort is independent of the original order of the array.

Answer: Improved heap sorting. After the array is sorted, each number is O(logK), a total of N numbers, and the overall time complexity is O(N*logK)


Sorting case two:

Determine whether there are duplicate values ​​in the array. The extra space complexity must be guaranteed to be O(1).

Idea: If there is no space complexity limit, use a hash table. Hash table implementation, time complexity is O(N), space complexity is O(N). Examine the classical sorting algorithm, the space complexity is limited.

Answer: Sort first, and equal values ​​will be pasted together after sorting. Then judge. Heap sorting needs to be rewritten into a non-recursive version (the classic heap sorting is recursive)

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_32265569/article/details/109178992