剑指offer面试题4(java版):二维数组中的查找

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlehaes/article/details/91382715

welcome to my blog

面试题4:二维数组中的查找

题目描述

思路

  • 比较右上角的数字和要查找的数字的大小关系
  • 如果右上角的数字大于要查找的数字, 则忽略右上角数字所在的列
  • 如果右上角的数字小于要查找的数字, 则忽略右上角数字所在的行

复杂度

  • 时间复杂度:
  • 空间复杂度:
public class Solution {
    public boolean Find(int target, int [][] array) {
        // 健壮性判断
        if(array.length <=0 ){
            return false;
        }
        // 正式判断; 判断右上角的元素和要查找的元素的大小关系, 结果有三种可能: 1,忽略列, 2,忽略行, 3,返回true   把这三种情况想清楚了, 这题就简单了
        int row = 0;
        int col = array[0].length - 1;
        while(row <= array.length - 1 && col >= 0){
            if(array[row][col] == target)
                return true;
            else if(array[row][col] > target)
                col--;
            else 
                row++;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/littlehaes/article/details/91382715