《剑指offer》面试题3 二维数组中的查找 Java版

(二维数组,每行递增,每列递增。输入二维数组和一个整数,判断数组中是否含有此数。)

我的方法:拿到题目,根据题目条件我提取出这样一个特性:一个数的右边和下面的数都比它大。于是就可以写出一种递归的方法:从左上角开始寻找,针对当前被检查的数字,如果相等返回true;如果小于target我们继续向右和向下寻找;如果大于target就不必继续寻找下去了(因为我们向右或向下寻找只会继续增大)。


public class SearchIn2DArray {
    public static boolean find(int[][] a, int target){
        // 指针为空 或者 {}或者{{}}
        if(a == null || a.length == 0 || (a.length == 1 && a[0].length == 0)){
            return false;
        }
        return search(a, target, 0, 0);
    }

    private static boolean search(int[][] a, int target, int row, int col){
        if(row >= a.length || col >= a[0].length){
            return false;
        }
        if(a[row][col] > target){
            return false;
        }else if(a[row][col] == target){
            return true;
        }else return search(a, target, row+1, col) || search(a, target, row, col+1);
    }   
}

书中方法:解决复杂问题,一个很有效的方法是从一个具体的问题入手,通过分析简单的例子,寻找到普通的规律。书上的思路是从右上角开始,向左或者向下去寻找目标,也是利用了左边的数字比当前数字小,下面的数字比当前数字大这个特点。

public class SearchIn2DArray {  
    public boolean find2(int[][] a, int target){
        if(a == null || a.length == 0 || (a.length == 1 && a[0].length == 0)){
            return false;
        }
        int rowNow = 0;
        int colNow = a[0].length-1;

        while(rowNow < a.length && colNow >= 0){
            if(a[rowNow][colNow] == target){
                return true;
            }else if(a[rowNow][colNow] > target){
                rowNow ++;
            }else if(a[rowNow][colNow] < target){
                colNow --;
            }
        }

        return false;
    }
}

原文地址:https://www.cnblogs.com/czjk/p/11233173.html