Question:
There is such a two-dimensional matrix A [n] [N], satisfying j <k, 1) A [I] [J] <A [I] [k]; 2) A [J] [I] <A [k] [I] (in fact, the data is decreased from the upper left corner to the lower right corner), given a number target, how to quickly search whether the two-dimensional coordinates are output in the matrix; otherwise, null is output. (assume that the data is not repeated)
For example
12 34 56 78 90 96
13 35 57 79 91 97
14 36 58 80 93 98
15 37 59 81 94 99
16 38 60 82 95 120
17 39 61 83 100 123
Search for 60 and output <4, 2>
Practice: traverse the matrix from the lower left corner, that is, make I = n-1, j = 0. If the value of (I, j) is greater than the search value, then I --, if it is small, J ++ is found. If it is equal, it is found.
Code:
void find(int array[][6], int n, int target){ int i = n - 1, j = 0; while(i >= 0 && j < n) { if(array[i][j] == target) { cout << '(' << i << ',' << j << ')' << endl; return; } else if(array[i][j] > target) i--; else j++; } cout << "NULL\n";}
Result:
12
(0, 0)
34
(0, 1)
56
(0, 2)
78
(0, 3)
99
(3, 5)
123
(5, 5)
11
Null
20140920 search for a two-dimensional matrix of Baidu pen questions