1. The title knowledge
Find array
2. Title Description
Given a two-dimensional array, which each row from left to right in ascending order, from top to bottom is in ascending order. Given a number, this number determines whether or not the two-dimensional array.
E.g:
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
3. Problem-solving ideas
Required time complexity O (M + N), the spatial complexity is O (1). Where M is the number of rows, N being the number of columns.
A number of two-dimensional array, which is smaller than a certain number of its left, which is greater than a certain number, in its lower side. Therefore, start looking from the top right, you can narrow down the range depending on the size relationship between the target and the current element, the element of the current search interval for all elements of the lower left corner.
4. Code
public boolean Find(int target, int[][] array) {
int row = array.length;
int col = array[0].length;
if (array == null || row == 0 || col == 0) {
return false;
}
int i = 0, j = col - 1;// 从右上角元素开始
while (i < row && j >= 0) {
if (target > array[i][j]) {
i++;
}else if (target < array[i][j]) {
j--;
}else {
return true;
}
}
return false;
}