# 66 front-end algorithm interview questions with train of thought analysis to help you find leaks and fill vacancies

Time：2021-9-19

This part is mainly the notes cavszhouyou made during the practice of sword finger offer, which mainly involves the relevant knowledge of the algorithm and the notes made during some relevant interview questions. Share this summary with you to help you have a comprehensive leak detection and troubleshooting of the algorithm. Thank the original author cavszhouyou for his efforts. The original link is placed at the bottom of the article. If there is an error, I hope you can point it out together!

# 1. Search in two-dimensional array

``````Title:
In a two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete a function and enter such
A two-dimensional array and an integer to judge whether the array contains the integer.``````

Idea:

(1) The first method is to use two-layer loops to traverse in turn to determine whether it contains the integer. The worst-case time complexity of this method is O (n ^ 2).

(2) The second way is to use the characteristics of incremental sequence. We can traverse from the upper right corner of the two-dimensional array. If the current value is smaller than the desired number, move the position down
And then judge. If the current value is larger than the required number, move the position to the left and judge again. The worst-case time complexity of this method is O (n).

# 2. Replace spaces

``````Title:

Please implement a function to replace spaces in a string with "% 20". For example, when the string is we are happy. The replaced string is we% 20
Are%20Happy

Idea:

Replace the space with "% 20" using a regular expression combined with the replace method of the string

str.replace(/\s/g,"%20")``````

# 3. Print the linked list from end to end

``````Title:
Enter a linked list and print the value of each node of the linked list from end to end.

Idea:

Using the stack, first traverse the linked list node according to the head node, and add the node to the stack. When the traversal is completed, the elements in the stack are ejected and printed to achieve this. Stack
The implementation can be simulated by using the push and pop methods of array.``````

# 4. Rebuild binary tree

``````Title:

Enter the results of preorder traversal and inorder traversal of a binary tree, please rebuild the binary tree. It is assumed that the input pre order traversal and middle order traversal results do not contain duplicate numbers. For example, lose
Enter the preorder traversal sequence {1,2,4,7,3,5,6,8} and the middle order traversal sequence {4,7,2,1,5,3,8,6}, reconstruct the binary tree and return.

Idea:

First, the first element in the sequence must be the root element. Then we go to the middle order traversal to find the position of the element, and find the left position of the element
The edge part is the left subtree of the root node, and the right part is the right subtree of the root node. Therefore, we can intercept the corresponding parts respectively for recursive construction of subtree. In this way
The time complexity is O (n) and the space complexity is O (logn).``````

# 5. Implement queue with two stacks

``````Title:

Two stacks are used to implement a queue to complete the push and pop operations of the queue.

Idea:

A basic feature of queues is that elements are first in, first out. When simulating through two stacks, we first divide the two stacks into stack 1 and stack 2. When the push operation of the queue is executed, the
Push the element into stack 1. When the queue performs pop operation, first judge whether stack 2 is empty. If it is not empty, directly pop the element. If stack 2 is empty, it will be stored in stack 1
All elements of pop are then pushed to stack 2, and then the pop operation of stack 2 is performed.

Extension:

When two stacks of different lengths are used to simulate a queue, the maximum length of the queue is twice the length of the shorter stack.``````

# 6. Rotate the minimum number of the array

``````Title:

Moving the first elements of an array to the end of the array is called array rotation. Enter a rotation of a non decreasing sorted array, and output the rotation of the array
Minimum element. For example, if the array {3,4,5,1,2} is a rotation of {1,2,3,4,5}, the minimum value of the array is 1. Note: all elements given are greater than 0, if the array is large
Small is 0, please return 0.

Idea:

(1) What we input is a rotation of a non decreasing sorted array, so the value of the original array is incremented or repeated. After rotation, the value of the original array must match a value
Neighbor, and does not satisfy the increasing relationship. Therefore, we can traverse to find a pair of values that do not meet the increasing relationship, and the latter value is the minimum number of the rotating array.

(2) Dichotomy``````

For relevant information, please refer to:
Minimum number of rotating arrays

# 7. Fibonacci series

``````Title:

We all know the Fibonacci sequence. Now it is required to input an integer n. please output the nth item of the Fibonacci sequence. n<=39

Idea:

The law of Fibonacci sequence is that the first term is 0, the second term is 1, and the values after the third term are equal to the sum of the first two terms. Therefore, we can continue to iterate through iteration
Add to realize the construction of the nth value. It is realized by loop rather than recursion. The time complexity is reduced to o (n) and the space complexity is O (1).``````

# 8. Step jumping

``````Title:

A frog can jump up one step or two steps at a time. Find out how many jumping methods the frog can jump up an n-step.

Idea:

The problem of jumping steps is a dynamic programming problem. Because you can only jump one or two steps at a time, there are two schemes to jump to N steps. One is to jump from n-1 and the other is to jump from n-1
One is to jump from level n-2, so f (n) = f (n-1) + F (n-2).

It is similar to the Fibonacci sequence, but the values of the first two terms become 1 and 2, and the value of each subsequent term is equal to the sum of the first two terms.``````

# 9. Step jumping

Title:

A frog can jump up 1 step or 2 steps at a time… It can also jump up n steps. Find out how many jumping methods the frog can jump up an n-step.

Idea:

The problem of abnormal step jumping is the same as the thinking scheme of the previous problem. We can draw a conclusion that the value of each item is equal to the sum of the values of all the previous items.

f(1) = 1
F (2) = f (2-1) + F (2-2) / / F (2-2) represents the number of times to skip order 2 at a time.
f(3) = f(3-1) + f(3-2) + f(3-3)

f(n) = f(n-1) + f(n-2) + f(n-3) + … + f(n-(n-1)) + f(n-n)

Summarize again

``````        | 1 ,(n=0 )
f(n) =  | 1 ,(n=1 )
| 2\*f(n-1),(n>=2)``````

# 10. Rectangular cover

``````Title:

We can use a small rectangle of 2 * 1 to cover a larger rectangle horizontally or vertically. Please cover a large rectangle of 2 \ * n with n small rectangles of 2 * 1 without overlapping. Total
How many methods are there?

Idea:

It is still the application of Fibonacci sequence``````

# 11. Number of 1 in binary

``````Title:

Enter an integer and output the number of 1 in the binary representation of the number. Where negative numbers are represented by complements.

Idea:

A binary representation of a non-zero integer must have a bit of 1. We find the rightmost bit 1. When we subtract 1 from the integer, the rightmost bit 1 becomes 0, and then
All bits of the face are reversed, so by adding the minus one value to the original value, we can eliminate the rightmost bit 1. Therefore, judging the number of 1 in a binary, we can judge
How many times can you go through this process.

For example: 1100 & 1011 = 1000``````

# 12. Integer power of value

``````Title:

Given a floating-point number of type double, base and an integer exponent of type int. Find the exponent power of base.

Idea:

First, we need to judge whether the exponent is positive or negative and zero value, and realize it by recursion according to different situations.``````

# 13. Adjust the array order so that odd numbers precede even numbers

``````Title:

Enter an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array
Part, and ensure that the relative position between odd and odd, even and even remains unchanged.

Idea:

Because we need to consider the stability after adjustment, we can use the auxiliary array. First, the elements in the array are traversed, and each odd number is added to the array
In the odd auxiliary array, every time an even number is encountered, it will be put into the even auxiliary array. Finally, merge the two arrays. The time complexity of this method is O (n), space
The complexity is O (n).``````

# 14. The penultimate node in the linked list

``````Title:

Input a linked list and output the penultimate node in the linked list.

Idea:

Using two pointers, first make the first and second pointers point to the head node, and then make the second pointer take step k-1 to reach the k-th node. Then the two pointers go back at the same time
When the second pointer reaches the end, the first pointer points to the penultimate node.``````

``````Title:

Input a linked list and output all elements of the linked list after reversing the linked list.

Idea:

Three variables pre, current and next are set to save the previous node, current node and subsequent node respectively. Traverse backward from the first node. First, when
Save the successor node of the previous node to next, and then set the successor node of the current node to pre, and then set pre to the current node and current to ne
XT node to realize the next cycle.``````

# 16. Merge two sorted linked lists

``````Title:

Input two monotonically increasing linked lists and output the combined linked list. Of course, we need the combined linked list to meet the monotonic non decreasing rule.

Idea:

The elements of the two linked lists are compared recursively.``````

# 17. Substructure of tree

``````Title:

Input two binary trees a and B to judge whether B is the substructure of A. (PS: we agree that an empty tree is not a substructure of any tree)

Idea:

Through the idea of recursion

The first step starts from the root node of tree a, and finds the node R with the same value as the root node of tree B in the left and right subtrees.
In the second step, the two trees are traversed in the same traversal way from the R node and the root node at the same time, and the corresponding values are compared in turn. When the traversal of tree B ends, the comparison ends.``````

# 18. Binary tree image

``````Title:

Operate the given binary tree and transform it into a mirror of the source binary tree.

Idea:

Starting from the root node, first save the reference of the left subtree through temporary variables, and then exchange the reference of the left and right subtrees of the root node. Then recursively exchange the subtrees of the left and right nodes.``````

# 19. Print matrix clockwise

``````Title:

Enter a matrix and print out each number in clockwise order from the outside to the inside,
For example, if you enter the following matrix: 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Then print the numbers 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11 and 10 in turn

Idea:

(1) The data printed by one rotation can be located according to the upper left corner and lower right corner. After one rotation printing, move forward and backward one unit to the opposite corner respectively to determine the next rotation
The range of data to be printed at this time.

(2) Use the simulated magic cube counterclockwise solution. For each line printed, rotate the matrix 90 degrees counterclockwise, print the next line, and repeat in turn.``````

# 20. Define a stack to implement the Min function

``````Title:

To define the data structure of the stack, please implement a min function that can get the smallest element of the stack in this type.

Idea:

Use an auxiliary stack. Each time you press data into the data stack, press the smallest value in the current stack into the auxiliary stack. In this way, the top data of the auxiliary stack is always the smallest in the data stack
Value of.``````

# 21. Push in and pop-up of stack

``````Title:

Enter two integer sequences. The first sequence represents the push in order of the stack. Please judge whether the second sequence is the pop-up order of the stack. Assume that all the numbers pushed into the stack are not equal. for example
Sequence 1,2,3,4,5 is the pressing sequence of a stack. Sequence 4,5,3,2,1 is a pop-up sequence corresponding to the pressing sequence, but 4,3,5,1,2 cannot be the pressing sequence
Pop up sequence of columns. (Note: the length of the two sequences is equal)

Idea:

We can use an auxiliary stack. First, we traverse the stack pressing sequence and press the elements into the auxiliary stack in turn. After each element is pressed, we first judge whether the element is related to the output
The elements at the current position in the stack sequence are equal. If they are not equal, the elements will continue to press the stack. If they are equal, the top elements in the auxiliary stack will be out of the stack. After they are out of the stack, they will be in the stack sequence
Move the position of one bit back to continue the comparison. After the stack pressing sequence is traversed, if the auxiliary stack is not empty, it indicates that the stack pressing sequence is incorrect.``````

# 22. Print binary tree from top to bottom

``````Title:

Each node of the binary tree is printed from top to bottom, and the nodes of the same layer are printed from left to right.

Idea:

It is essentially a sequence traversal of binary tree, which can be realized through queue. First queue the root node. Then, the queue is dequeued. Each time the queue is dequeued, the left and right children of the dequeued element are
Nodes are added to the queue in turn, and the traversal ends when the queue length becomes 0.``````

# 23. Post order traversal of binary search tree

``````Title:

Enter an integer array to determine whether the array is the result of post order traversal of a binary search tree. If yes, yes is output; otherwise, no is output. Suppose any two of the input array
The two numbers are different from each other.

Idea:

For the postorder traversal of a legitimate binary tree, the last element is the root element. The element in front of the element can be divided into two parts. One part is the left subtree of the element,
The values of all elements are smaller than the root element, some are the right subtree of the element, and the values of all elements are larger than the root element. And each part is a legal sequence, so I
We can use these features to make recursive judgment.``````

# 24. Binary tree and path for a certain value

``````Title:

Enter a binary tree and an integer, and print out all paths where the sum of node values in the binary tree is the input integer. The path is defined as the path from the root node of the tree down to the leaf node
Passing nodes form a path.

Idea:

Through the depth first traversal of the tree, the value of the current node is saved during traversal and whether it is equal to the expected value is judged. If the traversal to the leaf node does not meet the requirements, it will be retreated.``````

# 25. Copy of complex linked list

``````Title:

Enter a complex linked list (each node has a node value and two pointers, one pointing to the next node and the other special pointer pointing to any node), and the return result is
The head of the copied complex linked list. (Note: please do not return the node reference in the parameter in the output result, otherwise the problem determination program will directly return null)

Idea:

(1) The first method is to copy each node of the original linked list and connect it through next. Then, after the linked list is copied, set the RA of each node
NDOM pointer. At this time, the random setting of each node needs to be traversed from the beginning, so the time complexity is O (n ^ 2).

(2) In the second way, first copy each node of the original linked list, and use map to save the original node and the copied node in the form of key value pairs. When the linked list is complex
After the system is completed, set the random pointer of each node. At this time, we can obtain the corresponding replication node through the key value relationship in the map
The time complexity is reduced to o (n), but the space complexity is changed to o (n). This is a practice of exchanging space for time.

(3) The third way is to copy each node of the original linked list, and add the copied node to the back of the original node. After the linked list is copied, it can be copied again
For the setting of random pointer, since each node is followed by its own replication node, we can easily obtain that random points to the corresponding replication node
。 Finally, the linked list is separated. Through this method, we can also reduce the time complexity to o (n).``````

# 26. Binary search tree and bidirectional linked list

``````Title:

Enter a binary search tree and convert the binary search tree into a sorted two-way linked list. It is required that no new node can be created, and only the node pointer in the tree can be adjusted.

Idea:

If we need to generate a sorted two-way list, we should adjust the tree structure by middle order traversal, because only middle order traversal, the return is a sort from small to large
Sequence.

The basic idea is that we first traverse from the root node, adjust the left subtree to a two-way linked list, point the pointer of the end element of the two-way linked list of the left subtree to the root node, and
Point the left node of the root node to the end node. Then adjust the right subtree to a two-way linked list, point the pointer of the head element of the two-way linked list of the right subtree to the root element, and then the root node
The right node of points to the header node. Through the recursive adjustment of the left and right subtrees, the construction of the sorted two-way linked list is realized.``````

# 27. Arrangement of strings

``````Title:

Enter a string and print out all the permutations of characters in the string in dictionary order. For example, if you enter the string ABC, all the characters that can be arranged by the characters a, B and C will be printed
The strings ABC, ACB, BAC, BCA, cab and CBA. Input Description: enter a string with a length of no more than 9 (there may be repeated characters), and the characters only include uppercase and lowercase letters.

Idea:

We can think of a string as two parts. The first part is its first character and the second part is all the characters after it. Find a full arrangement of the whole string, which can
The first step is to find all the characters that may appear in the first position, that is, to exchange the first character with all the subsequent characters. The second step is to find one of all the following characters
A full permutation. Therefore, in this way, we can recursively find the full arrangement of the current string.``````

Arrangement of strings

# 28. Numbers that appear more than half the times in the array

``````Title:

A number in the array appears more than half the length of the array. Please find out this number. For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Due to number
Word 2 appears five times in the array, more than half the length of the array, so output 2. If it does not exist, 0 is output.

Idea:

(1) Sort the array, and the median after sorting is the desired number. The time complexity of this method depends on the time complexity of the sorting method we use, so the fastest is
O(nlogn)。

(2) Since the number of numbers is more than half the length of the array, the median after sorting is the number. Therefore, we can simplify the problem to find the in an array
Digit problem. In fact, arrays do not need full sorting, only partial sorting. We implement this by using the partition function in the fast queue. We now have the following in the array
The machine selects a number, and then returns the index of the number in the array through the partition function. If the index is just equal to N / 2, then this number
It is the median of the array, that is, the required number. If the index is greater than N / 2, the median must be on the left of the index. Just continue to look on the left, and vice versa
Look on the right. In this way, you can only search on one side of the index instead of sorting on both sides, which reduces the sorting time by half. The time complexity of this method is O (n).

(3) Since this number appears more than the sum of the occurrences of all other numbers, you can consider saving two values when traversing the array: one is a number in the array
Word, one is the number of times. When traversing to the next number, if the next number is the same as the previously saved number, the number will be increased by 1. If it is different, the number will be reduced by 1. If
If the number of times is 0, you need to save the next number and set the number of times to 1. Because the number we're looking for appears more often than the sum of all the other numbers,
The number to be found must be the number corresponding to the last time the number is set to 1. The time complexity of the method is O (n) and the space complexity is O (1).``````

Numbers that appear more than half

# 29. Minimum number of K

``````Title:

Enter n integers to find the smallest number of K. For example, if you enter 8 numbers 4,5,1,6,2,7,3,8, the minimum 4 numbers are 1,2,3,4.

Idea:

(1) The first idea is to sort the array first, and then take the minimum K number. The time complexity of this method depends on the time complexity of the sorting algorithm we choose
Degree, the best case is O (nlogn).

(2) The second idea is that we only need to obtain the minimum K numbers, which are not necessarily sorted in order. Therefore, we can use part in quick sort
Implementation of the session function. Select a hub value each time, divide the array into two parts larger than the hub value and smaller than the hub value, and judge the position of the hub value
If the position of the new value is k-1, then the hub value and all the numbers in front of it are the minimum number of K. If the position of the pivot value is less than k-1, it is assumed that the pivot
If the position of the new value is n-1, then we have found the first n small number, we still need to go to the second half to find the value of K-N small in the second half for delimitation
Points. When the position of the hub value is larger than k-1, it indicates that the smallest K values are still in the left half, and we need to continue to divide the left half. This method is flat
The average time complexity is O (n).

(3) The third method is to maintain a maximum heap of capacity K. When traversing the array, if the capacity of the heap has not reached K, the elements are directly added to the heap
It is equivalent to assuming that the first k numbers are the smallest K numbers. When traversing an element after K, we compare the element with the maximum value of the heap. If it is more than the maximum value
If the value is small, then we exchange the maximum value with it, then adjust the heap. If it is greater than or equal to the maximum value of the heap, continue to traverse backward until the array traversal is completed. This
The average time complexity of the two methods is O (nlogk).``````

Finding the minimum number of K

# 30. Maximum sum of continuous subarrays

``````Title:

Hz occasionally uses some professional questions to fool those non computer majors. Today, after the meeting of the test group, he spoke again: in ancient one-dimensional pattern recognition, it is often necessary to calculate
Calculate the maximum sum of continuous sub vectors. When the vectors are all positive, the problem is well solved. However, if the vector contains a negative number, should it contain a negative number and expect the next one
Will positive numbers make up for it? For example: {6, - 3, - 2,7, - 15,1,2,2}, the maximum sum of continuous sub vectors is 8 (from the 0 to the 3). Will you be fooled by him
Live? (the length of the subvector is at least 1)

Idea:

(1) The first idea is to solve the problem directly. First, start the superposition with the first number, and then save the maximum value in the superposition process. Then start with the second number
Start stacking later and compare with the previously saved maximum value. The time complexity of this method is O (n ^ 2).

(2) The second idea is that first, we observe the law of a continuous array of maximum sum. We can find that the subarray must start with a positive number and contain positive and negative numbers in the middle.
Therefore, we can stack backward from the first number and save the maximum value each time. If the superimposed value is negative, the superimposed value is initialized to 0 because the subsequent number is plus negative
The number will only be smaller, so you need to find the next positive number to start the judgment of the next sub array. Judge back until the array traversal is completed to get the maximum value.
The time complexity of using this method is O (n).``````

Maximum sum of continuous subarrays

# 31. Number of occurrences of 1 in integer (to be understood in depth)

``````Title:

Find the number of occurrences of 1 in integers 1 ~ 13, and calculate the number of occurrences of 1 in integers 100 ~ 1# 300? For this reason, he counted the numbers 1, 10, 11, 1 in 1 ~ 13
12. Therefore, there were six times, but he had no way to solve the latter problem. Acmer hopes you can help him and make the problem more general. You can quickly find any nonnegative integer
The number of occurrences of 1 in the number interval.

Idea:

(1) The first idea is to directly traverse each number, and then judge the number of 1 in each number and stack it all the time.

(2) The second idea is to find the number of times 1 appears on each, and then stack it.``````

The number of occurrences of 1 in integers from 1 to N: O (logn) algorithm

# 32. Arrange the array into the smallest number

``````Title:

Enter a positive integer array, splice all the numbers in the array into a number, and print the smallest of all the numbers that can be spliced. For example, enter the array {3, 32321
}, the minimum number that these three numbers can be arranged is 321323.

Idea:

(1) Find out the full arrangement of the array, and then compare the results of each arrangement.

(2) The sorting algorithm is used to realize the comparison, but the comparison is not the size of the two elements, but the size of the positive sequence splicing and reverse sequence splicing of the two elements. If the reverse sequence splicing is correct
If the result is smaller, the positions of the two elements are exchanged. After sorting, the order of the array is the order of the smallest decimal.``````

Arranging arrays into the smallest number

# 33. Ugly number (to be further understood)

``````Title:

A number containing only prime factors 2, 3 and 5 is called an ugly number. For example, 6 and 8 are ugly numbers, but 14 is not because it contains a factor of 7. Traditionally, we regard 1 as the first ugly number. seek
The nth ugly number in descending order.

Idea:

(1) To judge whether a number is ugly, you can judge whether the number is continuously divided by 2 and whether the final remainder is 1. Judge whether the number is divided by 3 and whether the last remainder is 1. Judge constantly divided by
5. Whether the last remainder is 1. Without considering the time complexity, you can traverse to find the nth ugly number in turn.

(2) Use an array to save the sorted ugly numbers, and the later ugly numbers are generated from the front.``````

# 34. The first character that appears only once

``````Title:

Find the first character that appears only once in a string (1 < = string length < = 10000, all composed of uppercase letters) and return its position.

Idea:

(1) The first idea is to traverse each character from front to back. Each time a character is traversed, the character is compared with all subsequent characters to determine whether it contains the same character. this
The time complexity of one method is O (n ^ 2).

(2) The second idea is to first traverse the string, and store the characters and the number of characters in the form of key value pairs in the map structure. Then the second traversal
, go to the map to get the number of occurrences of the corresponding character and find the first character that appears only once. The time complexity of this method is O (n).``````

# 35. Reverse order pairs in the array

``````Title:

Two numbers in the array. If the previous number is greater than the following number, the two numbers form an inverse pair. Enter an array and find the reverse pairs in the array
Total number of P.

Idea:

(1) The first idea is to solve it directly by scanning the whole array in sequence. Each time a number is scanned, the size of the number and the number after it are compared one by one. If
If the following number is smaller than it, the two numbers form an inverse pair. Suppose the array contains n numbers. Because each number has to be compared with O (n) numbers
Therefore, the time complexity of this algorithm is O (n ^ 2).

(2) The second method is to use merge sort. When merging sort is performed after decomposition, the statistics of reverse order pairs are performed. This method is time-consuming
The degree is O (nlogn).``````

Inverse pairs in arrays

# 36. The first common node of two linked lists

``````Title:

Enter two linked lists and find their first common node.

Idea:

(1) The first method is to traverse each node in sequence on the first linked list. When traversing a node, it will traverse each node in sequence on the second linked list. If in the second
A node on a linked list is the same as the node on the first linked list, indicating that the two linked lists coincide on this node, so their common node is found. If first
The length of one linked list is m, and the length of the second linked list is n. The time complexity of this method is O (MN).

(2) The second way is to use the stack. Through observation, we can find that the common nodes of the two linked lists are located at the tail of the linked list, so we can use the two stacks respectively
, put the linked list elements on the stack in turn. Then, the elements are out of the stack at the same time in the two stacks, and the nodes out of the stack are compared. The last same node is the public node we are looking for. this
The time complexity of one method is O (M + n) and the space complexity is O (M + n).

(3) The third way is to traverse two linked lists respectively to get the length of the two linked lists. Then get the difference between the length of the longer list and the shorter list. We use two
Pointer to traverse the two linked lists respectively. First move the pointer of the longer linked list by N steps. N is the difference between the lengths of the two linked lists, and then move the two pointers at the same time,
Judge whether the pointed node is the same node. The time complexity of this method is O (M + n), and no additional space is required for the previous method.``````

The first common node of two linked lists

# 37. Number of occurrences of a number in a sorted array

``````Title:

Count a number: the number of occurrences in the sorted array. For example, enter the sort array {1, 2, 3, 3, 3, 4, 5} and the number 3, because 3 is out of this array
4 times, so output 4.

Idea:

(1) The first method is to directly traverse the array in order. This method is used to count the number of occurrences of numbers. The time complexity of this method is O (n).

(2) The second method is to use the binary search method. Because the array is a sorted array, the same numbers are arranged together. Statistics appear, we need
To find the beginning and end of the number, so as to determine the number of times the number appears. Therefore, we can use binary search to determine the beginning and end of the number
Location. If the middle value of our array is k for the first time, and if the value of K is greater than the evaluated value, we only need to judge the first part next time, such as
If the value of K is smaller than the evaluated value, we only need to judge the latter part next time. If the value of K is equal to the evaluated value, we need to judge the value
Whether it is the start position or the end position. If it is the start position, we need to look for the end position in the second half next time. If it's the end position, then we
Next time, you need to go to the first half to find the starting position. If it is neither the start position nor the end position, we will go to the front and back parts to find the start and end respectively
Beam position. The average time complexity of this method is O (logn).``````

# 38. Depth of binary tree

``````Title:

Enter a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing from root node to leaf node form a path of the tree, and the length of the longest path is the depth of the tree
Degrees.

Idea:

The depth of the root node is equal to the larger value of the left and right depth plus one, so it can be realized through recursive traversal.``````

# 39. Balanced binary tree

``````Title:

Enter a binary tree to judge whether the binary tree is a balanced binary tree.

Idea:

(1) When traversing each node of the tree, call the function to get the depth of its left and right subtrees. If the depth difference between the left and right subtrees of each node is no more than 1, it
Is a balanced binary tree. When using this method, the node will be traversed many times, so it will cause the problem of low efficiency.

(2) When finding the depth of a node, judge whether it is balanced at the same time. If it is unbalanced, - 1 is returned directly; otherwise, the tree height is returned. If the depth of a subtree of a node
If the degree is - 1, it will directly return - 1 upward, and the tree is already unbalanced. In this way, the node can only be accessed once.``````

# 40. A number that appears only once in the array

``````Title:

In an integer array, all but two numbers appear twice. Please write a program to find these two numbers that only appear once.

Idea:

(1) The first way is to traverse the array in turn and record the number of times the number appears, so as to find two numbers that appear only once.

(2) In the second way, according to the XOR property of bit operation, we can know whether two identical numbers are XOR equal to 0, whether a number and 0 are XOR or itself. Because in the array
The other numbers in the array appear in pairs, so we can XOR all the numbers in the array in turn. If only one number appears once, then the last one is left
Is the single number. If two numbers appear only once, then the last thing left is the result of the XOR of the two numbers. 1 in this result represents a and B
B different bits. We take the digit of the first 1 of the XOR result, if it is the third digit, and then divide the array into two groups by comparing the third digit. The same number must be the same
Be divided into the same group. After grouping, according to the idea of sequential XOR, the remaining numbers are two numbers that appear only once.``````

# 41. Continuous positive sequence with sum s

``````Title:

Xiao Ming likes math very much. One day when he was doing his math homework, he asked to calculate the sum of 9 ~ 16. He immediately wrote the correct answer is 100. But he was not satisfied with it. He was trying to find out
How many consecutive positive number sequences have a sum of 100 (including at least two numbers). Before long, he got another set of sequences with a continuous positive sum of 100: 18, 19, 20, 21, 22.
Now let's leave the problem to you. Can you quickly find all the sequences of continuous positive numbers with sum s? Good Luck! Output Description: outputs all continuous positive number sequences with sum s. order
The columns are in the order from small to large, and the sequences are in the order from small to large.

Idea:

Maintain a positive sequence array. The array initially contains only values 1 and 2, and then traverse backward from 3. Each element traversed is added to the sequence array, and then
Determine the sum of the sequence array at this time. If the sum of the sequence array is greater than the evaluated value, the first element (the smallest element) is ejected. If the sum of the sequence array is less than the evaluated value, continue
After traversing, add elements to the sequence and continue to judge. When the sum of the sequence array is equal to the evaluated value, print out the positive sequence at this time, and then continue to traverse back to find the next sequence
Continue the sequence until the array traversal is completed.``````

Sequence of continuous positive numbers with sum s

# 42. And are two numbers of S

``````Title:

Enter an incrementally sorted array and a number s, and find two numbers in the array. Yes, their sum is exactly S. if the sum of multiple pairs of numbers is equal to s, output two numbers
The product of is the smallest. Output Description: output two numbers corresponding to each test case, and the small one is output first.

Idea:

First, we can find that the greater the difference between two numbers, the smaller the product. So we just need to start from the beginning and end of the array to find the first pair of sums
Is the number of S. Therefore, we can use double pointers. The left pointer initially points to the first element of the array and the right pointer initially points to the last element of the array
。 Then first judge whether the sum of the numbers pointed to by the two pointers is s. if it is s, the numbers pointed to by the two pointers are the number pairs we need to find. If the sum of two numbers
If it is smaller than s, move the left pointer one bit to the left and continue to judge. If the sum of the two numbers is greater than s, move the right pointer one bit to the right and continue to judge.``````

String with S

# 43. Left rotation string

``````Title:

There is a shift instruction in assembly language called cyclic left shift (ROL). Now there is a simple task to simulate the operation result of this instruction with a string. For a given
Character sequence s, please rotate it to the left to shift the sequence output after k bits. For example, the character sequence s = "abcxyzdef" requires the output of the result after the cyclic left shift of 3 bits, that is, "X"
YZdefabc”。 Isn't it simple? OK, take care of it!

Idea:

String splicing after clipping``````

# 44. Flip the word order column

``````Title:

Fish, a new employee of Niuke recently, always takes an English magazine and writes some sentences in the book every morning. My colleague cat is very interested in the content written by fish
One day he borrowed fish to look through it, but he couldn't understand its meaning. For example, "student. A am I". Later I realized that this guy had reversed the order of sentences and words
, the correct sentence should be "I am a student.". Cat is not good at reversing the order of these words one by one. Can you help him?

Idea:

Separate the words with spaces, then reverse the array and re splice it into a string.``````

# 45. The surplus of playing cards

``````Title:

Ll is in a very good mood today because he went to buy a deck of playing cards and found that there were two kings and two Xiaowang (a deck of cards was originally 54 ^ \ ^)... He took them out at random
After five cards, he wanted to test his luck and see if he could draw shunzi. If he did, he decided to buy a sports lottery, hehe!! "Hearts a, spades 3, Wang, Wang"
, fangpian 5 "," oh my God! "Is not shunzi..... Ll is unhappy. He thinks about it and decides that DA / Xiao Wang can be regarded as any number, a as 1 and j as 11,
Q is 12 and K is 13. The above five cards can become "1,2,3,4,5" (the big and small kings are regarded as 2 and 4 respectively), "so lucky!". Ll decided to buy a sports lottery.
Now, ask you to use this card to simulate the above process, and then tell us how lucky ll is. For convenience, you can think that the size king is 0.

Idea:

First, judge whether the five numbers are continuous. The most intuitive way is to sort the array. It is worth noting that since 0 can be regarded as any number, we can use 0 to fill up the number
Vacancies in the group. If the sorted array is not continuous, that is, the two adjacent numbers are separated by several numbers, but as long as we have enough. You can fill in the blanks of these two numbers
No, this array is actually continuous.

So we need to do three things: first sort the array, then count the number of zeros in the array, and finally count the total number of vacancies between adjacent numbers in the sorted array. as
If the total number of vacancies is less than or equal to 0, then the array is continuous; otherwise, it is discontinuous. Finally, we also need to note that if the non-zero in the array
If the number repeats, the array is not continuous. The description of playing cards is that if a deck of cards contains pairs, it can't be shunzi.``````

Shunzi of playing cards

# 46. The last remaining number in the circle (Joseph Ring problem)

``````Title:

The N numbers 0, 1,..., n-1 are arranged in a circle. Starting from the number 0, the m-th number is deleted from the circle each time. Find the last number left in this circle
Word.

Idea:

(1) Use the ring linked list for simulation.

(2) According to the law (to be further understood)``````

The last remaining numbers in the circle

# 47. 1+2+3+…+n

``````Title:

For 1 + 2 + 3 +... + N, it is required that keywords such as multiplication and division, for, while, if, else, switch, case and conditional judgment statements (a? B: C) cannot be used.

Idea:

Since loop statements cannot be used, we can implement them by recursion. And because we can't use the conditional judgment operator, we can use the short circuit feature of the & & operator
Sex.``````

``````Title:

Write a function and find the sum of two integers. It is required that +, - ×、 ÷ four arithmetic symbols.

Idea:

Through bit operation, recursive implementation.``````

# 49. Convert a string to an integer.

``````Title:

Converting a string to an integer requires a library function that cannot convert an integer using a string. If the value is 0 or the string is not a legal value, 0 is returned. Input trace
Description: enter a string, including alphanumeric symbols, which can be empty. Output Description: if it is a legal numerical expression, this number will be returned; otherwise, 0 will be returned.

Idea:

Firstly, we need to judge the symbol. Secondly, we convert each string into an integer sum by subtracting 0, and stack it according to the number of bits in turn.``````

# 50. Duplicate numbers in array

``````Title:

All numbers in an array of length n are in the range of 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated
Each number is repeated several times. Please find any duplicate number in the array.

Idea:

(1) First sort the array, and then judge. The time complexity of this method is O (nlogn).

(2) Using the map structure, record the number of occurrences of each number in turn, so as to judge whether there are duplicate numbers. The time complexity of this method is o
(n) , the space complexity is O (n).

(3) The traversal starts from the head of the array. Each time a number is traversed, the number is compared with its subscript. If the number and subscript are different, the number and its corresponding subscript value are compared
Exchange. If the corresponding subscript value is already the correct value, it indicates that the current element is a duplicate number. This method does not need to be compared with the previous method

# 51. Build product array

``````Title:

Given an array a [0,1,..., n-1], please construct an array B [0,1,..., n-1], where the element B [i] = a  in B_ A_...* A[i-1]*A
[i+1]*...*A[n-1]。 Division cannot be used.

Idea:

（1）  C[i]=A×A×...×A[i-1]=C[i-1]×A[i-1]
D[i]=A[i+1]×...×A[n-1]=D[i+1]×A[i+1]
B[i]=C[i]×D[i]
The multiplication integral is divided into two parts, which are solved circularly respectively, and then multiplied.

(2) The above method requires additional memory space. We can introduce intermediate variables to reduce the space complexity. (to be further understood)``````

Building product arrays

# 52. Regular expression matching

``````Title:

Please implement a function to match including '.' and '' Regular expression for. The character '.' in the pattern represents any character, and '' Indicates that any character before it can appear
Meaning times (including 0 times). In this question, matching means that all characters of the string match the whole pattern. For example, the string "AAA" matches the patterns "A.A" and "ab * ac * a",
But it does not match "AA. A" and "ab \ * a".

Idea:

(1) State machine idea (to be further understood)``````

Regular expression matching

# 53. A string representing a numeric value

``````Title:

Please implement a function to determine whether the string represents a numeric value (including integer and decimal). For example, the strings "+ 100", "5e2", "123", "3.1416" and "- 1E"-
16 "all represent values. But" 12e "," 1a3.14 "," 1.2.3 "," + - 5 "and" 12e + 4.3 "are not

Idea:

Using regular expression``````

# 54. The first non repeating character in the character stream

``````Title:

Please implement a function to find the first character that appears only once in the character stream. For example, when only the first two characters "go" are read out from the character stream, the first one appears only once
The character is "g". When the first six characters "Google" are read from the character stream, the first character that appears only once is "L". Output Description: if the current character stream
If there is no character that appears once, return # character.

Idea:

Same as question 34``````

# 55. The entry node of the link in the linked list

``````Title:

A linked list contains rings. How to find the entry node of the ring?

Idea:

First, we can judge whether there are rings in the linked list by using the fast and slow pointers. When the fast and slow pointers meet, it indicates that there are rings in the linked list. The meeting point must exist in the ring, so I
You can use a pointer to move forward from this point. For each point you move, the length of the ring increases by one. When the pointer returns to this point again, the pointer goes one circle, so
Through this method, we can get the length of the ring in the linked list, and we record it as n.

Then we set two pointers, first point to the head node respectively, then move one pointer for N steps, and then move the two pointers at the same time. When the two pointers meet, they meet
The point is the entry node of the ring.``````

Sword finger offer — the entry node of the link in the linked list

# 56. Delete duplicate nodes in the linked list

``````Title:

In a sorted linked list, there are duplicate nodes. Please delete the duplicate nodes in the linked list. The duplicate nodes are not retained and the chain header pointer is returned. For example, linked list 1 - > 2 - > 3-

>After 3 - > 4 - > 4 - > 5 treatment, it is 1 - > 2 - > 5

Idea:

The first step to solve this problem is to determine the deleted parameters. Of course, this function needs to input the head node of the linked list to be deleted. The head node may duplicate the following nodes, that is, the head node

Next, we traverse the whole linked list from scratch. If the value of the current node is the same as that of the next node, they are duplicate nodes and can be deleted. To ensure deletion
After that, the linked list is still connected without intermediate disconnection. We should connect the current previous node with the node whose value is greater than that of the current node. We need to make sure prev
Always connect to the next node that has no duplicates.``````

# 57. Next node of binary tree

``````Title:

Given a binary tree and one of its nodes, how to find the next node in the middle order traversal order? The node in the tree has two pointers to the left and right child nodes respectively,
There is also a pointer to the parent node.

Idea:

This problem can be divided into three situations.

In the first case, the current node contains a right subtree. In this case, the next node traversed in the middle order is the leftmost child of the right subtree of the node. So we just need to start from the right child node
Go straight along the pointer of the left child node to find the next node.

In the second case, the current node does not contain a right subtree, and the current node is the left child node of the parent node. In this case, the next node traversed in the middle order is the parent node of the current node
Point.

In the third case, the current node does not contain a right subtree, and the current node is the right child node of the parent node. In this case, we look up along the parent node until we find it

# 58. Symmetric binary tree

``````Title:

Please implement a function to judge whether a binary tree is symmetrical. If a binary tree is the same as its mirror, it is symmetrical.

Idea:

When we pre traverse a binary tree, we first access the left child node, and then access the right child node. Therefore, we can define a symmetric preorder traversal
, that is, access the right child node first, and then access the left child node. By comparing whether the final results of the two traversal methods are the same, we can judge whether the binary tree is symmetric binary
Trees.``````

# 59. Print binary tree in zigzag order (to be further understood)

``````Title:

Please implement a function to print the binary tree in zigzag order, that is, the first line is printed from left to right, and the second layer is printed from right to left, that is, the first line is printed in zigzag order
Print from left to right, the second layer from right to left, the third line from left to right, and so on.

Idea:

Printing a binary tree in zigzag order requires two stacks. When printing a row of nodes, we save the child nodes of the next layer to the corresponding stack. If you are currently printing odd layers
, save the left child node first, and then save the right child node to a stack; If even layers are currently printed, save the right child node first, and then save the left child node to the second stack. each
After a stack traversal is completed, it enters the next layer loop.``````

Printing binary trees in zigzag order

# 60. Print the binary tree by layer from top to bottom, and the nodes of the same layer are output from left to right. Each layer outputs one line.

``````Title:

The binary tree is printed from top to bottom by layer, and the nodes of the same layer are printed from left to right, with one line for each layer.

Idea:

A queue is used to save the nodes to be printed. In order to print each row of the binary tree into one row separately, we need two variables: one variable indicates that it is still in the current layer
There are no printed nodes. Another variable represents the number of nodes next time.``````

# 61. Serialized binary tree (with in-depth understanding)

``````Title:

Please implement two functions to serialize and deserialize the binary tree respectively.

Idea:

Array simulation``````

# 62. The k-th node of the binary search tree

``````Title:

Given a binary search tree, please find the k-th smallest node.

Idea:

First, a tree is traversed in middle order. While traversing, the number of nodes that have been traversed is recorded. When traversing the k-th node, this node is the k-th largest node.``````

# 63. Median in data flow (to be further understood)

``````Title:

How to get the median in a data stream? If an odd number of values are read out from the data stream, the median is the value in the middle after all values are sorted. If data
If an even number of values are read out from the stream, the median is the average of the middle two numbers after all values are sorted.``````

# 64. Maximum value in sliding window (to be further understood)

``````Title:

Given an array and the size of the sliding window, find the maximum value in all sliding windows. For example, if you enter an array {2,3,4,2,6,2,5,1} and a sliding window
If the size is 3, there are 6 sliding windows, and their maximum values are {4,4,6,6,6,5}; The sliding window for the array {2,3,4,2,6,2,5,1} has the following
6: {[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]}。

Idea:

Simulation using queues``````

# 65. Paths in the matrix (to be further understood)

``````Title:

Please design a function to judge whether there is a path containing all characters of a string in a matrix. The path can start from any lattice in the matrix, and each
In one step, you can move a grid left, right, up and down in the matrix. If a path passes through a lattice in the matrix, the path cannot enter the lattice again
。 For example, a b c e s f c s a d e e matrix contains a path of the string "bcced", but the matrix does not contain a path of "ABCB", because the path of the string
After the first character B occupies the first row and the second lattice in the matrix, the path cannot enter the lattice again.``````

# 66. Range of motion of robot (to be further understood)

``````Title:

There is a square with M rows and N columns on the ground. A robot starts to move from the grid with coordinates 0,0. Each time, it can only move one grid in the left, right, upper and lower directions, but it can't
Enter the grid where the sum of digits of row coordinates and column coordinates is greater than k. For example, when k is 18, the robot can enter the grid (35,37) because 3 + 5 + 3 + 7 = 18. however
, it cannot enter the grid (35,38) because 3 + 5 + 3 + 8 = 19. How many grids can the robot reach?``````

# recommend

The author once again recommends the collection of this original text, which is included inCavszhouyou – front end interview review notes, this warehouse is the front-end review notes of the original author during the school recruitment. It mainly summarizes some important knowledge points and front-end interview questions. I hope it will be helpful to you.

Finally, if the articles and notes can give you a little help or inspiration, please don’t be stingy with your praise and collection. Your is certainly the biggest driving force for me to move forward

Note links are attached to read more high-quality articles in previous periods. You can check them step by step. You can praise and encourage me if you like:https://github.com/Wscats/art…

## Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]