解题思路
- 从数组右上角(左下角)开始遍历;
- 当target小于当前值,说明target在当前左边区域,删除当前值所在的列;
- 大于当前值,说明target在当前值下方,删除其所在的行;
- 等于当前值,直接返回true;
- 循坏完毕未找到,返回false;
Java Solution
class Solution {
public boolean findNumberIn2DArray(int[][] matrix, int target) {
// n次提交代码心得:matrix为null 和 matrix行列的长度不一样。
// 需要先判断数组是否为空,否则可能会出现空指针异常。
if(matrix != null && matrix.length>0 && matrix[0].length>0){
int raw = matrix.length;
int col = matrix[0].length;
int i = 0;
int j = col-1;
while(i<raw && j>=0){
if(target == matrix[i][j]){
return true;
}
else if(target < matrix[i][j]){
--j;
}
else{
++i;
}
}
}
return false;
}
}
注意
数组为空和数组长度为0的区别
- null是一个数组类型的空引用。不指向任何对象。对数组进行操作时,需要判断是否为空,否者会引起空指针异常。
- 而长度为0的数组称为“空数组”,空数组是一个对象,只是对象中包含的元素个数为0。
python Solution
class Solution(object):
def findNumberIn2DArray(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if matrix != None and len(matrix) > 0 and len(matrix[0]) > 0:
raws = len(matrix)
cols = len(matrix[0])
raw = 0
col = cols -1
while raw < raws and col >= 0:
if matrix[raw][col] == target:
return True
if matrix[raw][col] > target:
col -= 1
else:
raw += 1
return False