题目来源:https://www.nowcoder.com/practice/abc3fe2ce8e146608e868a70efebf62e?tpId=13&&tqId=11154&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
题解
解题思路:
- 因为该二维数组是排序的,所以从左到右、从上到下递增的。
- 所以,先从右上角开始比较。
- 如果
target < array[i][j]
,则左移,因为第j
列已经肯定是大于target
了 - 如果
target > array[i][j]
,则下移,因为第i
行已经肯定是小于target
了。 - 如果
target = array[i][j]
,则该数组中含有该整数。 - 遍历完数组都没有就返回
false
代码实现:
public class Solution {
public boolean Find(int target, int [][] array) {
// 边界条件判断
if (array == null || array.length == 0 ||
array[0] == null || array[0].length == 0) {
return false;
}
// 获取函数矩阵的行数 m 与列数 n
int m = array.length;
int n = array[0].length;
// 从右上角先比较,初始化一开始的元素位置,这里我们设置为矩阵最右上角的元素
int i = 0;
int j = n - 1;
// 循环遍历整个函数
while (i < m && j >= 0) {
// 如果目标值小于右上角的数字,则列下标减一
if (target < array[i][j]) {
j--;
}
// 如果目标值大于右上角的数字,则行下标加一
else if (target > array[i][j]) {
i++;
}
// 如果相等,直接 true
else {
return true;
}
}
// 循环结束后如果还没有找到目标时,返回 false
return false;
}
}