剑指offer 03二维数组的查找(java)

解题思路

  1. 从数组右上角(左下角)开始遍历;
  2. 当target小于当前值,说明target在当前左边区域,删除当前值所在的列;
  3. 大于当前值,说明target在当前值下方,删除其所在的行;
  4. 等于当前值,直接返回true;
  5. 循坏完毕未找到,返回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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值