Problem: In a two-dimensional array, each row is ordered in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, enter a two-dimensional array and an integer to determine if the array contains the integer. For example: In the following two-dimensional array to find whether there is 7, if present, return true, otherwise, return false.
1 |
2 |
8 |
9 |
2 |
4 |
9 |
12 |
4 |
7 |
10 |
13 |
6 |
8 |
11 |
15 |
at this point, perhaps the first time we see this issue will be very excited, take it for granted, such a simple question, why waste time, not just to do a traversal array it? But then carefully think about, the interviewer is not Daogaoyizhang, will not take such a mentally retarded question to interview you, he will certainly expect you to have a quick, time complexity of a smaller way to solve this simple problem. So, if you have a problem, don't rush to write the code, but you should study it and find the answer that the interviewer really wants.
This problem, in fact, we can put the start point in the upper right corner of the array. For example, to find a number larger than the upper-right corner of the number, then find the next line, no, the previous column to find. This way, you can delete a row at a time, reducing the number of traversal times. For example, the process of finding 7:
At this point, the equivalent of a total of 5 times we find the number we want to look for, the time complexity is: O (n).
According to the figure, it is also easy to write the code as follows:
# include <stdio.h>bool find (int matrix[][4], int rows, int columns, int number) {bool found = false;if (Matrix! = NUL L && rows > 0 && columns > 0) {int row = 0, column = Columns-1;while (row<rows && Column> ; =0) {if (matrix[row][column] = = number) {found = True;break;} else if (Matrix[row][column] > number) {column--;} else{row++;}}} return found;} int main (void) {int matrix[4][4] = {{1, 2, 8, 9}, {2, 4, 9, ten}, {4, 7,,, {6, 8, one, 15}};bool flag = Find (Matrix, 4 , 4, 7);//returns 1//bool flag = Find (Matrix, 4, 4, 5);//returns 0PRINTF ("%d\n", flag); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A sword offer--a number in a special array.