1.1024! How many zeros are there at the end?
The number of 0 at the end is determined by the number of factors 2 and 5 in the multiplication. Obviously, the number of factor 2 in multiplication is greater than 5, so we only need to count the number of Factor 5.
Number of multiples of 5: 1024/5 = 204
The number is a multiple of 25: 1024/25 = 40 (25 is 5*5, so 25 includes two 5)
Number of multiples of 125: 1024/125 = 8
Which is a multiple of 625: 1024/625 = 1
So 1024! A total of 204 + 40 + 8 + 1 = 253 factors 5.
That is, 1024! There are 253 0 at the end.
2. Given a data stream that contains endless search keywords (for example, keywords that people continuously enter during Google search ). How can we randomly select 1000 keywords from this endless stream?
Defines an array with a length of 1000.
The first 1000 keywords in the data stream must be put in the array.
For the n (n> 1000) keyword in the data stream, we know that the probability of this keyword being randomly selected is 1000/n. So weUse this keyword to replace the random one in the array with a probability of 1000/n.. This ensures that all keywords are selected with a probability of 1000/n.
We can make sure that 1000 random keywords are always stored in the array.
3. Sort the following expressions by complexity
2 ^ n ^ googol (googol = 10 ^ 100) n! N ^ n
The complexity is from low to high.
N ^ googol
2 ^ n
N!
N ^ n
4. Randomly select a point from the circle with a radius of 1.
Assume that the center of the circle is in the coordinate element (0, 0 ). Method 1.
Select a random point in the square of the X axis [-1, 1] and Y axis [-1, 1. Then, determine whether the vertex is in the circle (by calculating the distance from this vertex to the center of the circle ). If it is in the circle, this point is the result. If it is not in the circle, it is re-selected until it is found.
The square area is 4, and the circle area is pi. Therefore, the probability of random points in the Square within the circle is PI/4.
Method 2.
Select an angle randomly from [0, 2 * PI), corresponding to a radius in the circle, and then select a point on the radius. However, the points on the radius cannot be evenly selected. The selected probability should be proportional to the length from the center of the circle, so that the random points are evenly distributed within the circle.
5. How to randomly select a number for an integer stream with an unknown length?
Method 1. Save the entire integer stream to an array and then randomly select it.
If the integer stream is too long to be saved, this method cannot be used.
Method 2. If the integer stream ends after the first number, we will definitely select the first number as the random number.
If the integer stream ends after the second number, the probability of selecting the second number is 1/2. We replace the preceding random number with 1/2 with a probability of 2nd to obtain a new random number that meets the conditions.
....
If the integer stream ends after the nth number, the probability of the nth number is 1/N. We replace the selected random number with the nth number with the probability of 1/N to obtain a new random number that meets the conditions.
....
In this way, we only need to save a random number and the length of the integer stream to date. Therefore, you can process any long integer stream.
6. Design a data structure, which contains two functions: 1. Insert a number and 2. Obtain the middle number. And estimate the time complexity.
1. Use array storage.
Insert a number to the end of the array within the O (1) time.
When getting the number, find the number in the O (n) time. (Compare the first number of arrays with other numbers and divide them into two groups based on the size of the comparison results. Then we can determine the group in which the number is located. Further segment the group according to the same method until the middle number is found .)
2. Sort array storage.
When you insert a number, locate the position to be inserted in the O (logn) time, move the element in the O (n) time, and insert the new number to the appropriate position.
When a medium number is obtained, a medium number is found in the O (1) complexity.
3. Use a large root heap and a small root heap for storage.
Use a large root heap to store half of the smaller numbers, and use a small root heap to store half of the larger numbers.
When you insert a number, insert the number to the corresponding heap within the O (logn) time, and move the root node as appropriate to keep the two heap numbers equal (OR 1 difference ).
When getting the number, find the number in the O (1) time.
7. If a fixed-length array is specified, the incremental integer sequence is written into the array. When it is written to the end of the array, the returned array starts to be rewritten and overwrites the previously written number.
Find the given integer in this special array.
Suppose the array is a [0, 1,..., N-1].
We can adopt a binary search-like strategy.
First, compare a [0] And a [n/2]. If a [0] <A [n/2], it indicates a [0, 1 ,..., n/2] is an incremental subsequence. Otherwise, the other part is an incremental subsequence.
Then, judge whether the integer to be searched is within the ascending subsequence range. If yes, use the common Binary Search Method to continue searching. If not, repeat the search process until it is found or fails.
8. specify two sorted sequences to find the common elements.
Assume that the sequence is sorted in ascending order. Define two pointers pointing to the beginning of the sequence respectively.
If the two elements are equal, an identical element is found. If the two elements are not equal, the pointer pointing to the smaller element moves forward. Repeat the preceding steps until a pointer points to the end of the sequence. (They asked this question during my last interview. In the same score, if the two arrays are about the same size, use your method. If the array size is much different, just traverse the small ones and search for them in the big ones ~ )
9. Given a function that can generate integers 1 to 5 at random, write a function that can generate integers 1 to 7 at random.
The key to this question is to make the numbers from 1 to 7 have the same probability. As long as we can randomly select 1 to n numbers from N numbers, and perform this operation repeatedly until the last number is left.
We can call the given function n times to generate n random numbers between 1 and 5, and select the location of the maximum number to meet the above requirements.
For example
The initial number of 7 numbers [1, 2, 3, 4, 5, 6, 7].
7 random numbers from 1 to 5 [5, 3, 1, 4, 2, 5]
Then we reserve [, 7],
Three random numbers from 1 to 5 [2, 4, 1]
Then we keep the [6]
6 is the random number generated this time.
10. Determine whether a natural number is the square of a certain number. Of course, you cannot use open operations.
Assume that the number to be judged is N.
Method 1:
Traverse the numbers from 1 to n, obtain the square and compare them with N.
If the square is less than N, the traversal continues. If the square is equal to N, the system exits successfully. If the square is greater than N, the system fails to exit.
The complexity is O (n ^ 0.5 ).
Method 2:
Use the binary search method to determine the numbers between 1 and N.
The complexity is O (log n ).
Method 3:
Because
(N + 1) ^ 2
= N ^ 2 + 2n + 1,
=...
= 1 + (2*1 + 1) + (2*2 + 1) +... + (2 * n + 1)
Note that these items constitute an equal difference sequence (2 difference between each item ).
So we can compare the relationship between N-1, n-1-3, n-1-3-5... and 0.
If the value is greater than 0, the system continues to subtract. If the value is equal to 0, the system exits successfully. If the value is smaller than 0, the system fails to exit.
The complexity is O (n ^ 0.5 ). However, in method 3, multiplication in method 1 is replaced by addition and subtraction, so the speed is faster.
11. Given a data stream that contains endless search keywords (for example, keywords that people continuously enter during Google search ). How can we randomly select 1000 keywords from this endless stream?
Defines an array with a length of 1000. The first 1000 keywords in the data stream must be put in the array. For the n (n> 1000) keyword in the data stream, we know that the probability of this keyword being randomly selected is 1000/n. Therefore, we use this keyword to replace the random one in the array with a probability of 1000/n. This ensures that all keywords are selected with a probability of 1000/n. We can make sure that 1000 random keywords are always stored in the array.
12. Sort the following expressions by complexity
2 ^ n ^ googol (googol = 10 ^ 100) n! N ^ n
The complexity is from low to high.
N ^ googol 2 ^ n! N ^ n
13. Google pen: Randomly select a point in the circle with a radius of 1
Assume that the center of the circle is in the coordinate element (0, 0 ).
Method 1. Randomly select a point in the square of the X axis [-1, 1] and Y axis [-1, 1. Then, determine whether the vertex is in the circle (by calculating the distance from this vertex to the center of the circle ). If it is in the circle, this point is the result. If it is not in the circle, it is re-selected until it is found.
The square area is 4, and the circle area is pi. Therefore, the probability of random points in the Square within the circle is PI/4.
Method 2. Select an angle randomly from [0, 2 * PI), corresponding to a radius in the circle, and then select a point on the radius. However, the points on the radius cannot be evenly selected. The selected probability should be proportional to the length from the center of the circle, so that the random points are evenly distributed within the circle.
14. How to randomly select a number for an integer stream with an unknown length
Method 1. Save the entire integer stream to an array and then randomly select it.
If the integer stream is too long to be saved, this method cannot be used.
Method 2. If the integer stream ends after the first number, we will definitely select the first number as the random number.
If the integer stream ends after the second number, the probability of selecting the second number is 1/2. We replace the preceding random number with a probability of 1/2 with a number of 2nd to obtain a new random number that meets the conditions ..... If the integer stream ends after the nth number, the probability of the nth number is 1/N. We replace the selected random number with the nth number with the probability of 1/N to obtain a new random number that meets the conditions .....
In this way, we only need to save a random number and the length of the integer stream to date. Therefore, you can process any long integer stream.
15. Design a data structure, which contains two functions. 1. Insert a number and 2. Obtain the middle number. And estimate the time complexity.
1. Use array storage.
Insert a number to the end of the array within the O (1) time.
When getting the number, find the number in the O (n) time. (Compare the first number of arrays with other numbers and divide them into two groups based on the size of the comparison results. Then we can determine the group in which the number is located. Further segment the group according to the same method until the middle number is found .)
2. Sort array storage. When you insert a number, locate the position to be inserted in the O (logn) time, move the element in the O (n) time, and insert the new number to the appropriate position. When a medium number is obtained, a medium number is found in the O (1) complexity.
3. Use a large root heap and a small root heap for storage. Use a large root heap to store half of the smaller numbers, and use a small root heap to store half of the larger numbers. When you insert a number, insert the number to the corresponding heap within the O (logn) time, and move the root node as appropriate to keep the two heap numbers equal (OR 1 difference ). When getting the number, find the number in the O (1) time. Given a fixed-length array, the incremental integer sequence is written into this array. When it is written to the end of the array, the returned array starts to be rewritten and overwrites the previously written number. Find the given integer in this special array. Suppose the array is a [0, 1,..., N-1]. We can adopt a binary search-like strategy. First, compare a [0] And a [n/2]. If a [0] <A [n/2], it indicates a [0, 1 ,..., n/2] is an incremental subsequence. Otherwise, the other part is an incremental subsequence. Then, judge whether the integer to be searched is within the ascending subsequence range. If yes, use the common Binary Search Method to continue searching. If not, repeat the search process until it is found or fails. Specify two sorted sequences to find the common elements. Assume that the sequence is sorted in ascending order. Define two pointers pointing to the beginning of the sequence respectively. If the two elements are equal, an identical element is found. If the two elements are not equal, the pointer pointing to the smaller element moves forward. Repeat the preceding steps until a pointer points to the end of the sequence.
16. Find the MTH node at the bottom of the linked list.
Method 1: first, calculate the length N of the linked list in a traversal table. Then, traverse the table again and find the nth-MB node, that is, the MTH last node.
Method 2: Use two pointers to separate the nodes pointed to by the two pointers. Move the two pointers forward at the same time. When a pointer points to the last node, the second Pointer Points to the last M node. The complexity of both methods is O (n ). However, when n is large and M is small, method 2 may be faster. Because method 2 can make better use of the CPU cache.
Read more:
Http://baike.baidu.com/view/2089.htm CPU-> Cache
17 how to construct a binary sorting tree for a given sorting array?
Recursive algorithms are used. Select an element in the middle of the array as the root node. The element on the left constructs the left subtree, And the node on the right constructs a subtree.
18. Is there a sum of 10 numbers in the array?
1. Compare the sum of any two numbers to 10. For example
For (INT I = 0; I <n; ++ I) {for (Int J = I + 1; j <n ;++ J ){....}}
The complexity is O (n * n ).
2. After sorting the array, use binary search for each number M to search for 10-m in the array.
The complexity is O (nlogn ).
3. Store the array in hash_set. Find 10-m for each number of M in hash_set.
The complexity is O (n ).
4. If the array is large and exceeds the memory capacity, you can divide the data into G small groups according to hash (max (M, 10-m) % G. Then each small group is processed separately.
The complexity is O (n ).
19. Find the common characters of the two strings and sort them by one of them.
Write a function f (a, B). It carries two string parameters and returns a string of characters. This string is only contained in both strings and is in the order of. Write a version of the algorithm complexity O (N ^ 2) and an O (N)
O (N ^ 2): For each character in a, traverse each character in B. If the character is the same, copy it to the new string.
O (n): first, create a hash_map using the characters in B. For each character in a, check whether hash_map exists. If yes, copy it to the new string.
20. Given an integer sequence, some of which are negative and some are positive. Find the largest and subsequences from the sequence.For example:-5, 20,-4, 10,-18, subsequence [20,-4, 10] has the largest and 26.
Int getmaxsubarraysum (int * array, int array_len)
{
Int current_sum = 0;
Intmax_sum = 0;
For (INTI = 0; I <array_len; I ++)
{
Curren_sum + = array;
If (current_sum> max_sum)
{
Max_sum = current_sum;
}
Else if (current_sum <0)
{
Current_sum = 0;
}
}
Return max_sum;
}
Or int maxsum (int n, int * List)
{
Int ret, sum = 0;
Int I;
For (ret = list [I = 0]; I <n; I ++)
Sum = (sum> 0? Sum: 0) + list, ret = (sum> 0? Sum: Ret );
Return ret;
}
21. convert an undirected acyclic graph into a tree with the smallest depth
It is known that the information of all vertices and edges of a undirected graph T needs to be converted to a tree, which requires the minimum depth of the tree, design an algorithm to find the root nodes of all trees that meet the requirements and analyze the time-space complexity.
The simplest and most direct method is to try every node: Assume that a node is the root node and the depth of the computing tree is used. After traversing all the nodes, the root node with the minimum depth of the tree is found. However, this method is very complex. If there are n nodes, the time complexity is O (n ^ 2 ). The depth of the tree depends on the distance from the root node to the deepest leaf node, so we can start with the leaf node. The leaf node will be connected to only one node (the root node may be connected to only one node), so we can easily find all possible leaf nodes. The question can be equivalent to finding two leaf nodes, so that the distance between the two leaf nodes is the farthest. The root node is the center point of the two leaf node paths (or any of the two center points ). We can delete the node with a connection degree of 1 every time until only one or two nodes are left. Then, this node, or any of the two nodes, is the root node we are looking.
22. Place the lower-case letters in the string before the upper-case letters.
There is a string consisting of upper and lower cases. Now you need to modify it to put all the lower-case letters in front of the upper-case letters (the original order is not required between the upper and lower-case letters ). Initialize two int variables A and B, representing the two positions in the string. At the beginning, a points to the first character of the string, and B points to the last character of the string. Gradually increase the value of A to point to an upper-case letter, gradually reduce B to point to a lower-case letter, exchange the characters pointed to by a and B, and then continue to add, reduce B ..... When a> = B, the sorting is completed again. I points to the last lowercase character, and J points to the lower-case character.
Void swapstring (char * STR, intlen)
{
Inti = len-1, j = 0;
While (j <= I)
{
Boolflag1 = 0, flag2 = 0;
If (STR [I]> 'Z' | STR [I] <'A ')
{
I --;
}
Else
Flag1 = 1;
If (STR [J]> 'Z' | STR [J] <'A ')
{
J ++;
}
Else
Flag2 = 1;
If (flag1 & flag2)
{
Swap (STR [I], STR [J]);
}
}
}
23. What is the ratio of men to women in a country where male is preferred? Every family wants to have boys in a country where boys and girls are important. If the children they give birth to are girls, they will be reborn until the children are born. What is the ratio of men to women in such a country?
Or. Among all the First Children, the ratio of men to women is; among all the second children, the ratio of men to women is ;.... among all the children born with N, the ratio of men to women is. So the total proportion of men and women is.
24. how do I copy a special linked list? There is a special linked list. Each node not only has a pointer pnext to the next node, but also a pointer prand pointing to any node in the linked list. How do I copy this special linked list?
It is very easy to copy the pnext pointer, so the difficulty of the question is how to copy the prand pointer. Assume that the original linked list is A1-> A2->...-> An, and the new copied linked list is B1-> B2->...-> bn. In order to quickly find the node pointed to by prand and copy the corresponding link to B. We can combine the two linked lists into A1-> B1-> A2-> B2->...-> An-> bn. Starting from the A1 node, it is easy to find the node ax pointed to by the prand of A1, then find the Bx, and point the prand of B1 to the Bx to complete the prand copy of the B1 node. And so on. After the prand of all nodes is copied, you can divide the merged Linked List into two linked lists.
25 how to find a good person as soon as possible
There are n people, more than half of whom are good people, and the rest are bad people. Good people only tell the truth. Bad people may tell the truth or say false things. N people know each other as a good person or a bad person. Now you need to find a good person from these N people. You can only pick out two people each time, so that these two people can tell each other their identities. You can judge them based on their opinions. Ask how to find a good person as quickly as possible. (Consider the worst case) |
This is very similar to the chip test in Baidu interview questions. See:
Bytes.
26. What is the probability of a car driving over a highway in 30 minutes that is 0.95? (Assuming the condition is normal probability)
Assume that the probability of a car driving in 10 minutes is X, then the probability of not seeing the car driving is, and the probability of not seeing the car driving in 30 minutes is () ^ 3, that is 0.05. Therefore, the equation is obtained.
(_X) ^ 3 = 0.05
The formula X is about 0.63.
27. There are 25 horses, and only 5 horses can participate in each competition. How many times can I get the first three fastest running among 25 horses?
It must be at least 7 times.
First, divide the horse into five groups: A, B, C, D, and E. Each group has five horses and each group has a separate game. Then, place the first in each group in the competition. The result is as follows:
A0, A1, A2, A3, A4
B0, B1, B2, B3, B4
C0, C1, C2, C3, C4
D0, D1, D2, D3, D4
E0, E1, E2, E3, E4
Group A, Group B, group C, group D, and group E are arranged by rank (speed A0> A1> A2> A3> A4, group B0> B1 ....). And the result of the 6th match is A0> B0> C0> D0> E0.
After the first round, we know that the fastest one is A0.
We know that 2nd horses must be A1 or B0, so they will be included in the next competition. If A1 is fast, the first 3rd names are A2 or B0. If B0 is fast, the first 3rd names are A1, B1, or C0. That is to say, 2nd and 3rd names must be among A1, A2, B0, B1, and C0. Therefore, 7th and 2nd names can be obtained for these five horses in 3rd matches.
So we can get the first three horses in 7 matches.
28. Five pirates are listed in the order of 5 to 1. The largest pirate has the right to propose how to share 100 gold coins. But other people will vote on this. If the majority (the majority of all people) oppose this, they will be killed. What kind of solution should he propose, so that he can get as many gold coins as possible and won't be killed?
The allocation scheme is 98,0, 1.
Whether a fifth-level pirate will be killed depends on whether other pirates will gain more benefits after the fifth-level pirate's death. If you get more benefits, you will certainly oppose it. If you get less benefits, you will certainly support it. If the benefits do not change, you can both oppose or support it. If a fifth-level pirate dies, four levels of piracy are distributed, and four levels of piracy face the same problem. It depends on the change in interest distribution after their death. Then there are level 3 and level 2 pirates. No matter what a solution is proposed, no one of the second-level pirates will disagree with the majority of the people (for their own support, but the other party's opposition cannot constitute a majority of opposition ). So Level 2 pirates will certainly propose a, 0 allocation scheme, and they will enjoy all the gold coins. After you have guessed the distribution scheme of level 2 pirates, Level 3 pirates will propose a distribution scheme of, 0, and 1. In this way, level-1 piracy will support level-3 piracy because it has obtained more gold coins than level-2 piracy solutions. After you have guessed the distribution scheme of Level 3 pirates, Level 4 pirates will propose a distribution scheme of, 0, and. In this way, level 2 Pirates get more gold coins than the level 3 pirate solution, so they will support the level 4 pirate solution. After you have guessed the distribution scheme of 4-level pirates, 5-level pirates will propose the allocation scheme of, 0, and 1. In this way, level 1 and level 3 pirates obtain more gold coins than the level 4 pirate solution, so they will support the Level 5 pirate solution.
29. 4 people will go through a tent to return to their camp in the evening. Unfortunately, they only have one flashlight that can last for another 17 minutes. A flashlight is required to pass through the primary node, and each secondary node can only hold the size of two people. The four of them have different speeds. It takes one minute for the first to walk through the shard, two minutes for the second, five minutes for the third, and 10 minutes for the slowest one. How can they all go through the shard in 17 minutes?
1) The first and second are used together for 2 minutes;
2) It takes 1 minute to get the first one back;
3) use the third and fourth parts together for 10 minutes;
4) It will take 2 minutes for the second to return;
5) The first and second are used together for 2 minutes.
It takes 17 minutes in total.
30. How can I find a heavy one from eight balls?
You have 8 balls of the same size, 7 of which have the same weight and the other are heavy. How can I use the balance to retrieve the duplicate ball twice.
Answer: Take 6 first, and 3 on the same side of the balance. If the same weight is used, the remaining two are allowed. If the same weight is used, two of the three are called. Analysis: this problem can be solved by Reverse lookup. If we know that the heavy ball is in one or two balls, we can put one on both sides of the balance and compare the weight to find the heavy ball. If we know that the heavy ball is in a certain three balls, we can put one on each side of the balance. If it is the same weight, the third ball is the heavy ball. Otherwise, the heavier ball on the balance is the heavy ball. If we know that the heavy ball is larger than or equal to four balls, we cannot find the heavy ball through one weighing. So by weighing for the first time, we must limit the ball to one or two or three balls. In addition, the number of balls placed at both ends of the balance should be equal, otherwise the result is basically meaningless.
All possible comparison methods meeting the equality of balls at both ends
Left and right
1, 1
2, 2
3, 3
4, 4
Take into account that you must limit the ball to 2 or 3. For the first time, you can only use the comparison method of 3 or 3.
This question can also be extended: in a ball of the same size, m only has the same weight, and the other one has the same weight. Q: How many times does it take to obtain the duplicate goal?
From the above analysis, we can know that a maximum
-Find the duplicate from the three balls.
-Restrict the duplicate from 9 to 3.
-Restrict the heavy ball from 27 to 9.
.....
Therefore, you can obtain the duplicate ball from 3 ^ N at most N times. If you push it back, you can obtain the number of times M balls need to be called.
(There are three States on the balance: Left-heavy and left-light. If the balance is greater than N times, there can be at most 3 ^ n States, while the Bad ball has two states, the only special thing is that you can find the bad ball but do not know the weight of the Bad ball when n times are balanced, the M ball can have 2 (M-1) + 1 State so when there is a sufficient number of standard balls, 2 (M-1) + 1 ≤ 3 ^ n that m ≤ (3 ^ n + 1)/2)