The data structure array of typical programming questions

Source: Internet
Author: User

The data structure array of typical programming questions

Data structure has always been the focus of technical interviews. Most interview questions are centered on arrays, strings, linked lists, trees, stacks, and queues, therefore, each candidate must master these data structures.

Arrays and strings are two basic data structures. They store numbers and characters in continuous memory. Linked lists and trees are the most frequently used data structures during interviews. Because the linked list and Tree operations require a large number of pointers, the applicant must pay attention to the robustness of the code when solving related problems, otherwise the program may crash. Stack is a data structure closely related to recursion, and queues are also closely related to the breadth-first traversal algorithm. Understanding these two data structures can help us solve many algorithm problems.

Array

An array is the simplest data structure. It occupies a continuous memory and stores data in sequence. When creating an array, we need to first specify the size of the array and then allocate the memory according to the size. Even if we store only one number in the array, We need to allocate memory for all the data in advance. Therefore, the array space efficiency is not very good, and there are often idle areas that are not fully utilized.

Since the memory in the array is continuous, any element can be read/written at O (1) time according to the subscript, so its time efficiency is very high. We can use an array to implement a simple hash table based on the advantages of high array time efficiency: Set the subscript of the array to the key of the hash table ), set each number in the array to the value of the hash table, so that each subscript and the number corresponding to the subscript in the array form a key-value pair. With such a hash table, we can perform search in O (1) to quickly and efficiently solve many problems. Interview question 35 "the first letter appears only once" is a good example.

To solve the problem of low array space efficiency, we have designed and implemented a variety of dynamic arrays, such as the vector in STL of C ++. To avoid waste, we first open up a small space for the array and then add data to the array. When the number of data exceeds the capacity of the array, We need to allocate another larger space (each time the STL vector expands the capacity, the new capacity is twice the previous one ), copy the previous data to the new array, and then release the previous memory, which can reduce the memory waste. However, we also noticed that each time we expand the array capacity, there are a large number of additional operations, which has a negative impact on timeliness. Therefore, we should minimize the number of times to change the array capacity when using dynamic arrays.

In C/C ++, arrays and pointers are interrelated and different concepts. When we declare an array, its array name is also a pointer, which points to the first element of the array. We can use a pointer to access the array. But it is worth noting that C/C ++ does not record the size of the array. Therefore, when using pointers to access elements in the array, the programmer must ensure that it does not exceed the boundary of the array. The following example shows the differences between arrays and pointers. Run the following code. What is the output?

Int getsize (INT data [])

{

Return sizeof (data );

}

 

Int _ tmain (INT argc, _ tchar * argv [])

{

Int data1 [] = {1, 2, 3, 4, 5 };

Int size1 = sizeof (data1 );

 

Int * data2 = data1;

Int size2 = sizeof (data2 );

 

Int size3 = getsize (data1 );

 

Printf ("% d, % d, % d", size1, size2, size3 );

}

The answer is "20, 4, 4 ". Data1 is an array, and sizeof (data1) is an array size. This array contains five integers, each of which occupies 4 bytes, so the total length is 20 bytes. Data2 is declared as a pointer. Although it points to the first number of the array data1, it is essentially a pointer. In a 32-bit system, evaluate sizeof for any pointer. The result is 4. In C/C ++, when an array is passed as a function parameter, the array is automatically degraded to a pointer of the same type. Therefore, although the data parameter of the getsize function is declared as an array, it degrades to a pointer and the result of size3 is still 4.

Interview question 3: search in a two-dimensional array

Question: 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. Complete a function, input a two-dimensional array and an integer to determine whether the array contains the integer.

For example, the following two-dimensional array is the incremental sorting of each row and column. Returns true if the number 7 is queried in this array. returns false if the number 5 is queried because the array does not contain this number.

 

When analyzing this problem, many candidates will draw a two-dimensional array into a rectangle, and then select a number from the array to analyze the search process in three cases. When the number selected in the array is exactly the same as the number to be searched, the search process ends. If the selected number is smaller than the number to be searched, the number to be searched should be on the right or bottom of the selected position according to the array sorting rule (2.1 (). Similarly, if the selected number is greater than the number to be searched, the number to be searched should be on the top or left of the selected position (2.1 (B ).

Figure 2.1 search in a two-dimensional array

Note: select a number (dark box) in the middle of the array and determine the possible area (shadow part) of the number to be searched based on its size ).

In the above analysis, the number to be searched may appear in the two regions as compared to the currently selected location, and the two regions overlap, which seems complicated, so many people are stuck here to be helpless.

When we need to solve a complicated problem, a very effective way is to start with a specific problem and try to find a general rule by analyzing simple and specific examples. To solve this problem, we may also start with a specific example. Next, we will take the search for number 7 in the array given in the question as an example to analyze the search process step by step.

The problem we encountered earlier was that we selected a number in the middle of the two-dimensional array to compare it with the number to be searched, which led to the next search for two overlapping areas. If we select a number from the corner of the array to compare it with the number to be searched, will the situation become simpler?

First, select the number 9 in the upper-right corner of the array. Because 9 is greater than 7 and 9 is the first (minimum) number in the 4th column, 7 cannot appear in the column where the number 9 is located. Therefore, we remove this column from the region to be considered, and then we only need to analyze the remaining three columns (2.2 (). In the remaining matrix, the number in the upper right corner is 8. We can also remove the columns where 8 is larger than 7. Next, we only need to analyze the remaining two columns (as shown in 2.2 (B ).

In the array composed of the remaining two columns, number 2 is located in the upper right corner of the array. If 2 is less than 7, the 7 to be searched may be on the Right of 2, or under 2. In the previous step, we found that all columns on the Right of 2 have been removed, that is, 7 cannot appear on the Right of 2, so 7 can only appear under 2. Therefore, we can remove the row where number 2 is located and analyze only the remaining three rows and two columns of numbers (as shown in 2.2 (c ). In the remaining number, number 4 is located in the upper right corner. Like the preceding one, we delete the row where number 4 is located, and the remaining two rows and two columns of numbers (2.2 (D) are shown ).

In the remaining two rows, two columns, and four numbers, the number 7 in the upper right corner is the number 7 we are looking for, so the search process is complete.

 

Figure 2.2 steps to search for 7 in a two-dimensional array

Note: The area of the Shadow background in the matrix is the range of the next search.

To sum up the above search process, we find the following rule: first, select the number in the upper right corner of the array. If the number is equal to the number to be searched, the search process ends. If the number is greater than the number to be searched, the column where the number is located is removed. If the number is smaller than the number to be searched, remove the row where the number is located. That is to say, if the number to be searched is not in the upper-right corner of the array, a row or column is removed from the search range of the array each time, so that each step can narrow the search range, until the number to be searched is found or the search range is null.

After analyzing the entire search process, it is not difficult to write code again. The following is a reference code for the above ideas:

Bool find (int * matrix, int rows, intcolumns, int number)

{

Bool found = false;

 

If (Matrix! = NULL & rows> 0 & columns> 0)

{

Int ROW = 0;

Int column = columns-1;

While (row <rows & Column> = 0)

{

If (Matrix [row * columns + column] = number)

{

Found = true;

Break;

}

Else if (Matrix [row * columns + column]> Number)

-- Column;

Else

+ + Row;

}

}

 

Return found;

}

In the previous analysis, each time we select a number in the upper right corner of the array search range. Similarly, we can select numbers in the lower left corner. Interested readers may wish to analyze the search process in the lower left corner each time. However, you cannot select the upper left or lower right corner. Take the upper left corner as an example. The first number 1 is in the upper left corner of the initial array. Because 1 is smaller than 7, 7 is on the right or bottom of 1. At this time, we can neither remove the row where 1 is located from the search range, nor remove the column where 1 is located, so that we cannot narrow the search range.

Source code:

For the complete source code of this question, see the 03_findinpartiallysortedmatrix project.

Test cases:

The two-dimensional array contains the number to be searched (the number to be searched is the maximum and minimum values in the array, and the number to be searched is between the maximum and minimum values in the array ).

No number found in the two-dimensional array (the number to be searched is greater than the maximum value in the array, and the number to be searched is smaller than the minimum value in the array, the number to be searched is between the maximum and minimum values of the array, but this number is not in the array ).

Special input test (input NULL pointer ).

Exam point:

Measure the test taker's understanding and programming skills on two-dimensional arrays. Two-dimensional arrays occupy continuous space in the memory. Each row of elements is stored from top to bottom in the memory and left to right in the same row. Therefore, we can calculate the offset relative to the first address of the Array Based on the row number and column number to find the corresponding element.

Measure the test taker's knowledge about problem analysis. When a candidate finds that the problem is complex, it is critical that he or she identify the rule through specific examples. You only need to analyze this question from the upper right corner of a specific two-dimensional array, you can find the search rule and find a breakthrough to solve the problem.

 

 

This article is from the book "offoffoffer-famous enterprise interviewer excellent typical programming questions"

Book details: http://blog.csdn.net/broadview2006/article/details/7043805

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.